Java的几种Http请求使用比较

Http请求

常见的http客户端请求工具:

  • jdk HttpURLConnection
  • Apache HttpClient 比较常用
  • OkHttp 比较常用
  • hutool的HttpUtil

RestTemplate是一个同步的web http客户端请求模板工具
是基于spring框架的底层的一个知识点

OkHttp

依赖

        <!-- okHttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.1</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>logging-interceptor</artifactId>
            <version>3.9.1</version>
        </dependency>

优点

//用同一个socket连接向同一台主机发送请求
HTTP/2 support allows all requests to the same host to share a socket.
//连接池减少了延迟
Connection pooling reduces request latency (if HTTP/2 isn’t available).
//使用Gzip来减少压缩
Transparent GZIP shrinks download sizes.
//对同一个重复请求有应答缓存
Response caching avoids the network completely for repeat requests.

get与post请求使用

1.新建OkhttpClient

2.创建Request请求

3.创建Response

get

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

post

多了MediaType,和requestbody

url格式必须带http://

public static final MediaType JSON
    = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

HttpClient

依赖

        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.11</version>
        </dependency>

特点

1.基于标准、纯净的java语言。实现了Http1.0和Http1.1

get与post请求使用

1.创建CloseableHttpClient
2.创建httpPost:
设置url,entity,config,header
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(param,"UTF-8");
 RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build();
 httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 3.创建CloseableHttpResponse
 用EntityUtils.toString(res.getEntity())获取string类型返回内容
 4.关闭CloseableHttpClient,CloseableHttpResponse

hutool的HttpUtil

依赖

<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-all</artifactId>
   <version>5.7.16</version>
</dependency>

参数为url加String类型的request body,时间可以不选,直接使用工具类调用

String result = HttpUtil.post(webhookUrl, new WxCpGroupRobotMessage()
        .setMsgType(GroupRobotMsgType.TEXT)
        .setContent(content)
        .setMentionedList(mentionedList)
        .setMentionedMobileList(mobileList)
        .toJson(),180*1000);
log.info("微信发送完成,返回结果为{}",result);
posted @ 2022-08-26 17:19  yorkiiz  阅读(2303)  评论(0编辑  收藏  举报