一、OKHttp简介
初识OKHttp
OkHttp是一个处理网络请求的开源项目,是Android端一个较新的轻量级网络框架,支持HTTP/HTTPS协议、请求头设置、响应解析等功能,并且支持异步调用,因此在接口测试中也是一种非常优秀的选择。
OkHttp是一个高效的HTTP客户端,其特性包括:
- 支持HTTP/2,并且允许同一个主机地址的所有请求共享同一个socket连接,这样能减少服务器的请求次数
- 通过连接池,减少了请求延迟
- 透明的GZIP压缩,减少响应数据的大小
- 缓存响应内容,避免一些完全重复的请求
优缺点
优点
- OKHttp客户端易于使用,有完善的在线接口文档可供阅读;
- 它支持多种协议如HTTP/1.1、HTTP/2和websocket等,可满足不同场景下的需要;
- 它提供了异步请求和响应,可以提高性能和效率;
- 发送和接收数据时,OkHttpClient提供了丰富的API,可以自定义请求头、响应头及请求体等;
- 通过添加拦截器,可以方便对请求和响应做一些额外的处理,比如记录日志、添加认证等功能。
缺点
- 对于一些较为复杂的接口场景,需要编写更多的代码来实现功能;
- 在处理大量并发请求时,需要谨慎设计线程池和连接池参数,否则可能会影响系统性能。
访问地址
官网地址:https://square.github.io/okhttp/
GitHub地址:https://github.com/square/okhttp
接口文档地址:https://square.github.io/okhttp/3.x/okhttp/
二、OKHttp的使用
添加Maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
基本语法结构
- 创建一个OkHttpClient对象;
- 创建一个Request对象,构建请求,写对应的数据(url、请求数据等);
- 将Request对象封装为Call,通过Call 来执行同步或异步请求(调用execute方法同步执行,调用enqueue方法异步执行);
- 获取对应的响应数据;
- 关闭响应资源的操作。
三、案例Demo
GET请求(不带参数)
public static void getTest() throws IOException {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder() //默认是GET请求
.url("http://localhost:4568/getdemo")
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println("响应体结果为:"+result);
}
response.close();
}
GET请求(带参数)
private static void getWithParam() throws IOException {
String URL="http://localhost:4568";
OkHttpClient client=new OkHttpClient();
HttpUrl.Builder httpUrl=HttpUrl.parse(String.format("%s/getwithparam",URL))
.newBuilder()
.addQueryParameter("name","tom")
.addQueryParameter("age","10");
Request request=new Request.Builder()
.url(httpUrl.build())
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println(result);
}
response.close();
}
POST请求(form表单)
public static void postWithForm() throws IOException {
OkHttpClient client=new OkHttpClient();
RequestBody requestBody=new FormBody.Builder()
.add("name","tom")
.add("age","10")
.build();
Request request=new Request.Builder()
.url("http://localhost:4568/post/form/demo")
.post(requestBody)
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println(result);
}
response.close();
}
POST请求(json)
public static void postWithJson() throws IOException {
OkHttpClient client=new OkHttpClient();
String data="{\"name\": \"tom\", \"age\": \"10\"}";
RequestBody requestBody=RequestBody.create(data,MediaType.parse("application/json"));
Request request=new Request.Builder()
.url("http://localhost:4568/post/json/demo")
.post(requestBody)
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println("响应结果为:"+result);
}
response.close();
}
POST请求(文件上传)
public static void postWihtFile() throws IOException {
OkHttpClient client=new OkHttpClient();
MediaType mediaType=MediaType.parse("image/png");
File file=new File("\\data\\image\\test.png");
RequestBody requestBody=new MultipartBody.Builder().setType(MultipartBody.FORM)
// .addFormDataPart("参数名","文件名",RequestBody.create(文件地址,文件格式))
.addFormDataPart("fileData","test",RequestBody.create(file,mediaType))
.build();
Request request=new Request.Builder()
.url("http://localhost:8888/uploadfile")
.post(requestBody)
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println(result);
}
response.close();
}
PUT请求
public static void put() throws IOException {
OkHttpClient client=new OkHttpClient();
String URL="http://localhost:4568/put/demo";
RequestBody requestBody=new FormBody.Builder()
.add("name","tom")
.add("age","10")
.build();
Request request=new Request.Builder()
.url(URL)
.put(requestBody)
.build();
Response response=client.newCall(request).execute();
if (response.isSuccessful()){
String result=response.body().string();
System.out.println(result);
}
response.close();
}
DELETE请求
public static void delete() throws IOException {
OkHttpClient client=new OkHttpClient();
String param="1112";
String URL = String.format("http://localhost:4568/delete/demo/%s",param);
Request request=new Request.Builder()
.delete()
.url(URL)
.build();
Response response=client.newCall(request).execute();
if(response.isSuccessful()){
String result=response.body().string();
System.out.println(result);
}
response.close();
}