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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)