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

java对接第三方接口的三种方式本文详细介绍了在日常开发中使用 Java 进行 HTTP 请求时 HttpURLConne ApacheHttpCl Spring 的 RestTemplate 以及 HutoolHttpU

大家好,欢迎来到IT知识分享网。

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

3.Spring提供的RestTemplate;

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

HttpURLConnection调用方法

@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调用

@Slf4j public class CloseableHttpClientUtil { 
    / *url 第三方接口地址 *json 传入的报文体,可以是dto对象,string、json等 *header 额外传入的请求头参数 */ public static String doPost(String url, Object json,Map<String,String> 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<String> 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调用

@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<String> httpEntity = new HttpEntity<>(headers); //通用的方法exchange,这个方法需要你在调用的时候去指定请求类型,可以是get,post,也能是其它类型的请求 ResponseEntity<String> 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<String> httpEntity = new HttpEntity<>(requestStr, headers); ResponseEntity<String> 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; } } 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/127493.html

(0)
上一篇 2025-09-07 13:45
下一篇 2025-09-07 14:00

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信