【Java】汇总Java中发送HTTP请求的7种方式

今天在项目中发现一个功能模块是额外调用的外部服务,其采用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

CloseableHttpClient HTTP发送请求处理流程:
https://blog.csdn.net/weixin_41256550/article/details/108068434?spm=1001.2101.3001.6650.4&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-4-108068434-blog-100150762.235%5Ev28%5Epc_relevant_t0_download&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-4-108068434-blog-100150762.235%5Ev28%5Epc_relevant_t0_download&utm_relevant_index=9

汇总发送HTTP请求的7种方式:
1HttpURLConnection
使用JDK原生提供的net,无需其他jar包。
2HttpClient
 需要用到commons-httpclient-3.1.jar
3CloseableHttpClient
 需要用到httpclient-4.5.6.jar
4、okhttp
需要用到okhttp-3.10.0.jar
5Socket
使用JDK原生提供的net,无需其他jar包。
6RestTemplate
RestTemplate 是由Spring提供的一个HTTP请求工具。
比传统的ApacheHttpClient便捷许多,能够大大提高客户端的编写效率。
7Feign
spring-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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值