简介
依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
GET异步请求
异步GET请求的4个步骤:
- 创建OkHttpClient对象
- 通过Builder模式创建Request对象,参数必须有个url参数,可以通过Request.Builder设置更多的参数比如:header、method等
- 通过request的对象去构造得到一个Call对象,Call对象有execute()和cancel()等方法。
- 以异步的方式去执行请求,调用的是call.enqueue,将call加入调度队列,任务执行完成会在Callback中得到结果。
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request request = new Request.Builder()
.url("http://www.baidu.com")
.method("GET",null)
.build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
//请求失败执行的方法
@Override
public void onFailure(Call call, IOException e) {
}
//请求成功执行的方法
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.code());
System.out.println(response.isSuccessful());
System.out.println(response.body().string());
}
});
结果:
200
true
<!DOCTYPE html>......
GET同步请求
同步GET请求和异步GET请求基本一样,不同地方是同步请求调用Call的execute()方法,而异步请求调用call.enqueue()方法。
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
Request request = new Request.Builder()
.url("http://www.baidu.com")
.method("GET", null)
.build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.同步调用会阻塞主线程
try {
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
System.out.println(response.code());
System.out.println(response.isSuccessful());
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
POST异步请求-键值对
通过FormBody,添加多个String键值对,最后为Request添加post方法并传入formBody。
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建请求体对象,并设置键值对数据
RequestBody formBody = new FormBody.Builder()
.addEncoded("name", "杨")
.addEncoded("age", "10")
.build();
//3.创建Request对象,设置post请求方式,并添加请求体
Request request = new Request.Builder()
.url("http://api.1-blog.com/biz/bizserver/article/list.do")
.post(formBody)
.build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.请求加入调度,重写回调方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
response.body().string();
}
});
POST同步请求-键值对
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建请求体对象,并设置键值对数据
RequestBody formBody = new FormBody.Builder()
.addEncoded("name", "杨")
.addEncoded("age", "10")
.build();
//3.创建Request对象,设置post请求方式,并添加请求体
Request request = new Request.Builder()
.url("http://api.1-blog.com/biz/bizserver/article/list.do")
.post(formBody)
.build();
//3.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
//4.同步调用会阻塞主线程
try {
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
System.out.println(response.code());
System.out.println(response.isSuccessful());
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
POST同步请求-提交String
构造一个RequestBody对象,用它来携带我们要提交的数据。在构造 RequestBody 需要指定MediaType,用于描述请求/响应 body 的内容类型。
//1.创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
String body = "I am tom.";
//2.创建请求体对象,并设置请求体类型和请求体内容
RequestBody requestBody = RequestBody.create(mediaType, body);
//3.创建Request对象,设置post请求方式,并添加请求体
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
//4.创建一个call对象,参数就是Request请求对象
Call call = okHttpClient.newCall(request);
try {
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
System.out.println(response.code());
System.out.println(response.isSuccessful());
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
封装的工具类
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import shade.org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 封装 OkHttp 工具类
* @author yangqian
* @date 2019-06-20
*/
@Slf4j
public class OkHttpUtils {
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final byte[] LOCKER = new byte[0];
private static OkHttpUtils instance;
private OkHttpClient okHttpClient;
private OkHttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)//10秒连接超时
.writeTimeout(10, TimeUnit.SECONDS)//10m秒写入超时
.readTimeout(10, TimeUnit.SECONDS)//10秒读取超时
.build();
}
public static OkHttpUtils getInstance() {
if (instance == null) {
synchronized (LOCKER) {
if (instance == null) {
instance = new OkHttpUtils();
}
}
}
return instance;
}
public String doGet(String url){
if (isBlankUrl(url)){
return null;
}
Request request = getRequestForGet(url);
return commonRequest(request);
}
public String doGet(String url, HashMap<String, String> params){
if (isBlankUrl(url)){
return null;
}
Request request = getRequestForGet(url, params);
return commonRequest(request);
}
public String doPostJson(String url, String json){
if (isBlankUrl(url)){
return null;
}
Request request = getRequestForPostJson(url, json);
return commonRequest(request);
}
public String doPostForm(String url, Map<String, String> params){
if (isBlankUrl(url)) {
return null;
}
Request request = getRequestForPostForm(url, params);
return commonRequest(request);
}
private Boolean isBlankUrl(String url){
if (StringUtils.isBlank(url)){
log.info("url is not blank");
return true;
}else{
return false;
}
}
private String commonRequest(Request request){
String re = "";
try {
Call call = okHttpClient.newCall(request);
Response response = call.execute();
if (response.isSuccessful()){
re = response.body().string();
log.info("request url:{};response:{}", request.url().toString(), re);
}else {
log.info("request failure url:{};message:{}", request.url().toString(), response.message());
}
}catch (Exception e){
log.error("request execute failure", e);
}
return re;
}
private Request getRequestForPostJson(String url, String json) {
RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return request;
}
private Request getRequestForPostForm(String url, Map<String, String> params) {
if (params == null) {
params = new HashMap<>();
}
FormBody.Builder builder = new FormBody.Builder();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addEncoded(entry.getKey(), entry.getValue());
}
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
return request;
}
private Request getRequestForGet(String url, HashMap<String, String> params) {
Request request = new Request.Builder()
.url(getUrlStringForGet(url, params))
.build();
return request;
}
private Request getRequestForGet(String url) {
Request request = new Request.Builder()
.url(url)
.build();
return request;
}
private String getUrlStringForGet(String url, HashMap<String, String> params) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(url);
urlBuilder.append("?");
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
urlBuilder.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (Exception e) {
urlBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
}
}
return urlBuilder.toString();
}
}
参考
Okhttp3基本使用
Okhttp基本用法和流程分析
OkHttp使用介绍
OkHttp使用进阶 译自OkHttp Github官方教程