摘要:本文主要介绍okhttp3
的功能,和我封装的简单工具类,方便大家快速应用于自己的开发环境。
简介
HTTP是现代应用网络的方式。这是我们交换数据和媒体的方式。高效地执行HTTP可以使您的内容加载更快,并节省带宽。
okHttp是一个HTTP客户端,默认情况下是高效的
·HTTP/2支持允许对同一主机的所有请求共享一个套接字。
·连接池减少了请求延迟(如果HTTP/2不可用)。
透明GZIP缩小了下载大小。
响应缓存完全避免重复请求的网络。
OkHttpUtils
工具类
- 该类封装了
get,post,put,delete
方法 - 未捕捉
http
请求状态码 - 请求返回结果字符串
java
public class OkHttpUtils {
private static final OkHttpClient CLIENT = new OkHttpClient();
/**
* GET 请求
* @param url
* @param headerMap
* @return
* @throws Exception
*/
public static String get(String url, Map<String,String> headerMap) throws Exception{
Request.Builder requestBuilder = new Request.Builder().url(url);
handleRequestHeader(requestBuilder, headerMap);
return executeRequest(requestBuilder);
}
/**
* POST JSON请求
* @param url
* @param jsonStr
* @param headerMap
* @return
* @throws Exception
*/
public static String postJson(String url, String jsonStr, Map<String,String> headerMap) throws Exception{
MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.post(RequestBody.create(mediaType,jsonStr));
handleRequestHeader(requestBuilder, headerMap);
return executeRequest(requestBuilder);
}
/**
* 上传文件
* @param url
* @param file
* @param headerMap
* @return
* @throws Exception
*/
public static String postFile(String url, File file, Map<String,String> headerMap) throws Exception {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.post(requestBody);
handleRequestHeader(requestBuilder, headerMap);
return executeRequest(requestBuilder);
}
/**
* PUT 方法
* @param url
* @param jsonStr
* @param headerMap
* @return
* @throws Exception
*/
public static String putJson(String url, String jsonStr, Map<String,String> headerMap) throws Exception {
MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.put(RequestBody.create(mediaType,jsonStr));
handleRequestHeader(requestBuilder, headerMap);
return executeRequest(requestBuilder);
}
/**
* DELETE 方法
* @param url
* @param headerMap
* @return
* @throws Exception
*/
public static String delete(String url, Map<String,String> headerMap) throws Exception {
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.delete();
handleRequestHeader(requestBuilder, headerMap);
return executeRequest(requestBuilder);
}
/**
* 真实执行请求
* @param requestBuilder
* @return
* @throws IOException
*/
private static String executeRequest(Request.Builder requestBuilder) throws IOException {
try (Response response = CLIENT.newCall(requestBuilder.build()).execute()) {
if(null != response.body()){
return response.body().string();
}
}
return null;
}
/**
* 处理请求头
* @param requestBuilder
* @param headerMap
*/
private static void handleRequestHeader(Request.Builder requestBuilder,Map<String,String> headerMap){
if(null != headerMap && headerMap.size() > 0){
headerMap.forEach(requestBuilder::header);
}
}
}
单元测试
get
方法
url
后面的参数要自己提前拼接好,headerMap
是header
中传递的数据
java
@Test
void get() throws Exception {
String result = OkHttpUtils.get("http://localhost:8081/index/home?value=123", null);
log.info(result);
}
postJson
方法
url
上也可以带参数,jsonStr
是对象转为json
的字符串,headerMap
是header
中传递的数据
java
@Test
void postJson() throws Exception {
Student student = new Student();
student.setName("zhangsan");
String result = OkHttpUtils.postJson("http://localhost:8086/index/addStudent", JSON.toJSONString(student), null);
log.info(result);
}
postFile
url
上也可以带参数,file
是文件对象,headerMap
是header
中传递的数据
java
@Test
void postFile() throws Exception {
String result = OkHttpUtils.postFile("http://localhost:8086/index/upload", new File("C:\\Users\\lanzhuo\\Desktop\\测试数据集.csv"), null);
log.info(result);
}
putJson
和
postJson
类似
delete
和
get
类似
Interceptors
拦截器使用
拦截器就是在请求执行前可以进行数据的一系列改写操作,可以方便我们统一进行任务管理,官方文档square.github.io/okhttp/feat...
ApiUtils
示例
该案例在请求前添加了
token
ApiTokenInterceptor
拦截器
vbscript
@Slf4j
public class ApiTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
// 重新构建request,添加了token,实际业务按照大家的token构建算法来
Request request = chain.request().newBuilder().header("token","abc").build();
long t1 = System.nanoTime();
log.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
log.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
ApiUtils
拦截器
封装的方法
java
public class ApiUtils {
private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
.addInterceptor(new ApiTokenInterceptor())
.build();
public static String get(String url) throws Exception{
Request.Builder requestBuilder = new Request.Builder().url(url);
try (Response response = CLIENT.newCall(requestBuilder.build()).execute()) {
if(null != response.body()){
return response.body().string();
}
}
return null;
}
}
测试用例
csharp
@Test
void get() throws Exception {
String result = ApiUtils.get("http://127.0.0.1:8080/user/info?name=lisi");
System.out.println(result);
}
结果如下