今天在项目中发现一个功能模块是额外调用的外部服务,其采用CloseableHttpClient调用外部url中的接口……
public void handleHttp(String jsonParam, String url) { BufferedReader in = null; try { HttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); request.addHeader(HTTP.CONTENT_TYPE, "application/json"); StringEntity s = new StringEntity(jsonParam, Charset.forName("UTF-8")); s.setContentEncoding("UTF-8"); s.setContentType("application/json;charset=UTF-8"); request.setEntity(s); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8")); StringBuilder sb = new StringBuilder(); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line).append(NL); } in.close(); if (code == 200) { logger.info("接口:{},请求成功:" + sb.toString(), url); } else if (code == 500) { throw new TapException("服务器错误:" + sb + ",url:" + url); } else { throw new TapException("接口未知的情况,code=" + code + "," + sb + ",url:" + url); } } catch (Exception e) { throw new TapException("接口调用出现异常……"); }}
CloseableHttpClient HTTP发送请求处理流程:
汇总发送HTTP请求的7种方式:1、HttpURLConnection使用JDK原生提供的net,无需其他jar包。2、HttpClient 需要用到commons-httpclient-3.1.jar3、CloseableHttpClient 需要用到httpclient-4.5.6.jar4、okhttp需要用到okhttp-3.10.0.jar5、Socket使用JDK原生提供的net,无需其他jar包。6、RestTemplateRestTemplate 是由Spring提供的一个HTTP请求工具。比传统的Apache和HttpClient便捷许多,能够大大提高客户端的编写效率。7、Feignspring-cloud-starter-feign学习1:JAVA发送HTTP请求的多种方式总结https://blog.csdn.net/liuyunyihao/article/details/125262877?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-125262877-blog-108068434.235%5Ev28%5Epc_relevant_t0_download&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-125262877-blog-108068434.235%5Ev28%5Epc_relevant_t0_download&utm_relevant_index=2学习2:SpringBoot调用外部接口的三种方式https://mp.weixin.qq.com/s/R0-2tvk1WktcLiERqm_1gw
来源地址:https://blog.csdn.net/weixin_42369773/article/details/130050100