-
参考资料地址
1、https://juejin.im/post/581311cabf22ec0068826aff
2、https://www.jianshu.com/p/e0520fb19b4e
-
问题
- 1、Builder模式是什么?为什么采用它?
- 2、Okhttp3设计最精彩的地方是Interceptor(拦截器)
- 3、cookie机制是什么?如何请求时加入cookie,返回时更新cookie?
-
基础使用(get请求)
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url(yoururl)
.build();
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String resStr = response.body().string();
Log.e(TAG,resStr);
}
});
}
-
基础使用(post请求)
String url = "www.yaolai.com";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("id", "a26a03ac9f8a4968918e3bfd8555c040").build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
//json格式
final String resStr = response.body().string();
Log.e(TAG,resStr);
}
});
-
RequestBody的构建
1、由于get请求没有请求体,仅靠请求头的参数拼接
的方式来访问,而post的请求将
参数封装在了请求体中,
所以会比get多了一个创建RequestBody的过程。2、RequestBody包含三种类型(类似Content-Type):普通表单,json,文件。
普通表单(默认的形式):
RequestBody body = new FormBody.Builder() .add("id", "a26a03ac9f8a4968918e3bfd8555c040").build();
json形式:
MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "你的json");
文件形式:
1、下面代码演示的是图片的形式MediaType.parse("image/png"),其他的文件有对应的格式。
参考地址:http://www.w3school.com.cn/media/media_mimeref.asp
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)) .build();
-
cookie(基础)
cookie在请求的时候放在请求头,在返回时更新cookie
简单携带方式:
//请求时传递 (返回数据时更新,用sharepreference存)
Request request = new Request.Builder()
.url(url)
.header("Cookie", "xxx")
.build();
-
cookie(自动管理)
//下面代码 实现自动携带cookie请求,返回时自动更新
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl.host(), list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();