大家好,今天小编来分享一下工作中常用到的两种HTTP客户端库(OkHttp和HttpClient),它们在使用、性能和功能等方面有一些显著的区别。接下来,我会通过实际的代码示例,展示如何使用这些库进行HTTP请求和处理响应。希望接下来的内容,对大家的学习和工作带来帮助。
OkHttpClient
对象,然后创建Request
对象,最后通过Call
对象执行请求。enqueue
方法(1)使用OkHttp发送GET请求示例代码
/**
* 通过OkHttp客户端进行Get请求
* @param url
* @return
*/
public static String getByOkHttp(String url) {
//创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//创建请求
Request request = new Request.Builder()
.addHeader("Authorization", "") //设置请求头,用于鉴权使用
.url(url)
.get()
.build();
//发送请求并获取响应
try(Response response = client.newCall(request).execute()){
if(response.isSuccessful()){
return response.body().string();
}else {
throw new IOException("Unexpected code " + response.code());
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
(2)使用OkHttp发送POST请求(请求方式application/x-www-form-urlencoded)
/**
* 通过OkHttp客户端进行Post请求,参数格式表单形式
*/
public static String postByOkHttp(String url) {
//token信息,供鉴权使用
String token = "";
//创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//创建请求体(请求参数)
FormBody formBody = new FormBody.Builder()
.add("param1", "value1")
.add("param2", "value2")
.build();
//创建请求
Request request = new Request.Builder()
.addHeader("Authorization", token) //设置请求头,用于鉴权使用
.url(url)
.post(formBody)
.build();
//发送请求并获取响应
try(Response response = client.newCall(request).execute()){
if(response.isSuccessful()){
return response.body().string();
}else {
throw new IOException("Unexpected code " + response.code());
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
(3)使用OkHttp发送POST请求(请求方式application/json)
//通过OkHttp客户端进行Post请求,参数格式json形式
public static String postJsonByOkHttp(String url) {
//token信息,供鉴权使用
String token = "";
//创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//创建请求体(请求参数)
RequestParam param = new RequestParam();
param.setName("张三");
param.setAge(18);
String json = JSON.toJSONString(param);
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaType, json);
//创建请求
Request request = new Request.Builder()
.addHeader("Authorization", token) //设置请求头,用于鉴权使用
.url(url)
.post(requestBody)
.build();
//发送请求并获取响应
try(Response response = client.newCall(request).execute()){
if(response.isSuccessful()){
return response.body().string();
}else {
throw new IOException("Unexpected code " + response.code());
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
CloseableHttpClient
对象,然后创建具体的HTTP请求对象(如HttpGet
、HttpPost
等),最后调用execute
方法执行请求 。CloseableHttpAsyncClient
(1)使用HttpClient发送GET请求示例代码
/**
* 通过HttpClient进行Get请求
*/
public static String getHttpClient(String url) {
//创建HttpClient实例
try(CloseableHttpClient client = HttpClients.createDefault()){
//token信息
String token = "";
//创建HttpGet请求
HttpGet httpGet = new HttpGet(url);
//设置鉴权参数
httpGet.setHeader("Authorization", token);
//发送请求并获取响应
try(CloseableHttpResponse response = client.execute(httpGet)){
if(response.getStatusLine().getStatusCode() == 200){
System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
(2)使用HttpClient发送POST请求示例代码(访问方式application/x-www-form-urlencoded)
/**
* 通过HttpClient进行Post请求,参数格式表单形式
*/
public static String postFormByHttpClient(String url) {
//创建HttpClient实例
try(CloseableHttpClient client = HttpClients.createDefault()){
//创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
//设置鉴权参数
String token = "";
httpPost.setHeader("Authorization", token);
//设置请求参数
List params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//设置请求方式(表单形式)
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//发送请求并获取响应
try(CloseableHttpResponse response = client.execute(httpPost)){
if(response.getStatusLine().getStatusCode() == 200){
System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
(3)使用HttpClient发送POST请求示例代码(访问方式application/json)
/**
* 通过HttpClient进行Post请求,参数格式JSON形式
*/
public static String postJsonByHttpClient(String url) {
//创建HttpClient实例
try(CloseableHttpClient client = HttpClients.createDefault()){
//创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
//设置鉴权参数
String token = "";
httpPost.setHeader("Authorization", token);
//设置请求参数
RequestParam param = new RequestParam();
param.setName("张三");
param.setAge(18);
String json = JSON.toJSONString(param);
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
//设置请求方式(JSON形式)
httpPost.setHeader("Content-Type", "application/json");
//发送请求并获取响应
try(CloseableHttpResponse response = client.execute(httpPost)){
if(response.getStatusLine().getStatusCode() == 200){
System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
特性 | OkHttp | HttpClient |
---|---|---|
协议支持 | HTTP/2、SPDY(自动协商) | HTTP/1.1 |
连接池 | 自动复用连接,减少延迟 | 需手动配置连接池 |
GZIP 压缩 | 透明压缩请求体/响应体 | 需手动处理 |
缓存机制 | 内置磁盘缓存(可定制) | 无内置缓存,需自行实现 |
超时控制 | 统一全局或单请求超时 | 支持细粒度超时(连接、读取、请求) |
拦截器 | 支持(修改请求、日志、重试等) | 无原生拦截器,需扩展接口 |
异步请求 | 通过 enqueue() 实现 |
需使用 CloseableHttpAsyncClient |
Cookie 管理 | 内置 CookieJar 接口 |
需依赖 CookieStore 实现 |
本文介绍了OKHttp和HttpClient两个客户端的功能、适用场景等。同时,通过实际的示例代码,演示了如何发送GET和POST请求和处理响应内容。大家可以根据自己的项目需求,选择合适的HTTP客户端库实现高效、安全的通信。 有待改正的地方,欢迎各位朋友留言评论。