一.OkHttp简介
OkHttp是目前非常火的网络库,它有以下特性:
1.支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
2.连接池减少请求延时
3.透明的GZIP压缩减少响应数据的大小
4.缓存响应内容,避免一些完全重复的请求
二.OkHttp基本使用
可参考官网:OkHttp
- OkHttpClient:客户端对象
- Request:访问请求,Post请求中需要包含RequestBody
- RequestBody:请求数据,在Post请求中用到
- Response:即网络请求的响应结果
- MediaType:数据类型,用来表明数据是json,image,pdf等一系列格式
- client.newCall(request).execute():同步的请求方法
- client.newCall(request).enqueue(Callback callBack):异步的请求方法,但Callback是执行在子线程中的,因此不能在此进行UI更新操作
1.OkHttp Get请求
通过以下代码,就成功的发送了一个Get请求,并获取了响应.
//新建一个OkHttpClient对象
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
//创建一个request对象
Request request = new Request.Builder()
.url(url)
.get() //默认就是GET请求,可以不写
.build();
//获取响应并把响应体返回
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
同步请求,需要先创建一个请求对象Request,Request对象也是通过build方式创建,在Request的静态内部类Builder中定义了设置请求地址、请求方式、请求头的方法。
接着创建Call对象,Call对象可以理解为Request和Response之间的一个桥梁,最后通过Call对象的execute方法完成Response的读取,
总结同步请求的三个步骤如下:
- 创建OkHttpClient和Request对象。
- 将Request对象封装成Call对象。
- 调用Call的execute()方法发送同步请求。
已成功的示例:
/*
* 请求http get
*/
public static void test1() throws IOException {
String requestPath = "http://10.1.1.181:8081";
OkHttpClient client = new OkHttpClient.Builder()
//.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
.build();
Request request = new Request.Builder()
.url(requestPath).get().build();
Response response = client.newCall(request).execute();
System.out.println("get返回状态:" + response.code());
System.out.println("get返回结果:" + response.body().string());
response.close();
}
2.OkHttp Post请求
通过以下代码,就成功的发送了一个POST请求,请求中多了RequestBody对象来携带需要传输的数据,并获取了响应。
public static final MediaType JSON= MediaType.get("application/json; charset=utf-8");
//新建一个OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建一个request对象
//获取响应并把响应体返回
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();
}
}
1)创建一个OkHttpClient的实列:
OkHttpClient client = new OkHttpClient();
2)创建一个RequestBody对象(存放待提交的参数):
RequestBody body = RequestBody.create(JSON, json);
3)在Request.Builder中调用一下post()方法,并将RequestBody对象传入:
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
4)调用OkHttpClient的newCall()方法来创建一个Call对象,并调用它的execute()方法来发送请求并获取服务器返回的数据,写法如下:
Response response = client.newCall(request).execute();
//execute()同步请求,需要try和catch
//enqueue方法是异步请求
返回响应结果具体写法如下:
String responseData = response.body().string();
示例:
/*
* 请求http post
*/
public static void test2() throws IOException {
//{"userName":"admin","password":"lianShi2020"}
String username="admin";
String password="lian2020";
//请求参数
JSONObject json = new JSONObject();
json.put("userName", username);
json.put("password", password);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(json));
String url = "http://10.1.1.182:8081/scheduler/login";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
//.addHeader("Content-Type","application/json")
.post(requestBody)
.build();
Call call=client.newCall(request);
try {
Response response =call.execute();
System.out.println("get返回状态:" + response.code());
System.out.println("get返回结果:" + response.body().string());
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.Okhttp文件上传
//
4.Okhttp文件下载
//
三.OKhttp的引用
3.1、maven配置
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.3.0</version> </dependency> |
3.2引用
import okhttp3.*;
3.3使用(参考2OKhttp基本使用)