java对接第三方接口的三种方式

2024-04-18 1258阅读

在日常工作中,经常需要跟第三方系统对接,我们做为客户端,调用他们的接口进行业务处理,常用的几种调用方式有:

java对接第三方接口的三种方式
(图片来源网络,侵删)

1.原生的Java.net.HttpURLConnection(jdk);

2.再次封装的HttpClient、CloseableHttpClient(Apache);

3.Spring提供的RestTemplate;

当然还有其他工具类进行封装的接口,比如hutool的HttpUtil工具类,里面除了post、get请求外,还有下载文件的方法downloadFile等。

HttpURLConnection调用方法

HTTP正文的内容是通过OutputStream流写入,向流中写入的数据不会立即发送到网络,而是存在于内存缓冲区中,待流关闭时,根据写入的内容生成HTTP正文。

调用getInputStream()方法时,会返回一个输入流,用于从中读取服务器对于HTTP请求的返回报文

@Slf4j
public class HttpURLConnectionUtil {
   /**
     *
     * Description: 发送http请求发送post和json格式
     * @param url          请求URL
     * @param params    json格式的请求参数
     */
    public static String doPost(String url, String params) throws Exception {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        URL httpUrl = null; // HTTP URL类 用这个类来创建连接
        try {
            // 创建URL
            httpUrl = new URL(url);
            log.info("--------发起Http Post 请求 ------------- url:" + url + "---------params:" + params);
            // 建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //设置请求的方法为"POST",默认是GET
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);// 设置不要缓存
            conn.setInstanceFollowRedirects(true);
            //由于URLConnection在默认的情况下不允许输出,所以在请求输出流之前必须调用setDoOutput(true)
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            conn.setDoInput(true);
            //设置超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.connect();
            // POST请求
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                response.append(lines);
            }
            reader.close();
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            log.error("--------发起Http Post 请求 异常 {}-------------", e);
            throw new Exception(e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(String.valueOf(ex));
            }
        }
        return response.toString();
    }
}

CloseableHttpClient调用

CloseableHttpClient 是一个抽象类,实现了httpClient接口,也实现了java.io.Closeable;

支持连接池管理,可复用已建立的连接 PoolingHttpClientConnectionManager

通过 httpClient.close() 自动管理连接释放

支持HTTPS访问 HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);

@Slf4j
public class CloseableHttpClientUtil {
    /**
    *url 第三方接口地址
    *json 传入的报文体,可以是dto对象,string、json等
    *header 额外传入的请求头参数
    */    
  public static String doPost(String url, Object json,Map header) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost= new HttpPost(url);//post请求类型
        String result="";//返回结果
        String requestJson="";//发送报文体
        try {
            requestJson=JSONObject.toJSONString(json);
            log.info("发送地址:"+url+"发送报文:"+requestJson);
            //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8"));
            StringEntity s= new StringEntity(requestJson, "UTF-8");
               // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
               httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(s);
            if(header!=null){
                Set strings = header.keySet();
                for(String str:strings){
                    httpPost.setHeader(str,header.get(str));
                }
            }
            HttpResponse res = httpclient.execute(httpPost);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(res.getEntity());
                    //也可以把返回的报文转成json类型
                    // JSONObject  response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
             //此处可以加入记录日志的方法
            // 关闭连接,释放资源
           if (httpclient!= null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
        return result;
    }
}


RestTemplate调用

//可以在项目启动类中添加RestTemplate 的bean,后续就可以在代码中@Autowired引入。

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Slf4j
@Component
public class RestTemplateUtils {
    @Autowired
    private RestTemplate restTemplate;
    /**
     * get 请求 参数在url后面  http://xxxx?aa=xxx&page=0&size=10";
     * @param urls 
     * @return string
     */
    public String doGetRequest(String urls) {
        
        URI uri = UriComponentsBuilder.fromUriString(urls).build().toUri();
        log.info("请求接口:{}", urls);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(headers);
        //通用的方法exchange,这个方法需要你在调用的时候去指定请求类型,可以是get,post,也能是其它类型的请求
        ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
        if (responseEntity == null) {
            return null;
        }
        log.info("返回报文:{}", JSON.toJSONString(responseEntity));
        
        return responseEntity.getBody();
    }
    
    /**
     * post 请求 参数在 request里;
     * @param url, request
     * @return string
     */
    public String doPostRequest(String url, Object request){
        URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();
        String requestStr= JSONObject.toJSONString(request);
        log.info("请求接口:{}, 请求报文:{}", url, requestStr);
        HttpHeaders headers = new HttpHeaders();    
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(requestStr, headers);
        ResponseEntity responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
                
        if (responseEntity == null) {
            return null;
        }
        
        String seqResult = "";
        try {
            if(responseEntity.getBody() != null ) {        
                if(responseEntity.getBody().contains("9001")) {
                    seqResult = new String(responseEntity.getBody().getBytes("ISO8859-1"),"utf-8");
                }else {
                    seqResult = new String(responseEntity.getBody().getBytes(),"utf-8");    
                }                                            
            }
            
            log.info("返回报文:{}", seqResult);
            
        } catch (UnsupportedEncodingException e) {
            log.error("接口返回异常", e);
        }
        return seqResult;
    }
}
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]