-
參考資料地址
1、https://juejin.im/post/581311cabf22ec0068826aff
2、http://www.itdecent.cn/p/e0520fb19b4e
-
問(wèn)題
- 1、Builder模式是什么?為什么采用它?
- 2、Okhttp3設(shè)計(jì)最精彩的地方是Interceptor(攔截器)
- 3、cookie機(jī)制是什么?如何請(qǐng)求時(shí)加入cookie,返回時(shí)更新cookie?
-
基礎(chǔ)使用(get請(qǐng)求)
//創(chuàng)建okHttpClient對(duì)象
OkHttpClient mOkHttpClient = new OkHttpClient();
//創(chuàng)建一個(gè)Request
final Request request = new Request.Builder()
.url(yoururl)
.build();
Call call = mOkHttpClient.newCall(request);
//請(qǐng)求加入調(diào)度
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);
}
});
}
-
基礎(chǔ)使用(post請(qǐng)求)
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);
//請(qǐng)求加入調(diào)度
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的構(gòu)建
1、由于get請(qǐng)求沒(méi)有請(qǐng)求體,僅靠請(qǐng)求頭的參數(shù)拼接
的方式來(lái)訪問(wèn),而post的請(qǐng)求將
參數(shù)封裝在了請(qǐng)求體中,
所以會(huì)比get多了一個(gè)創(chuàng)建RequestBody的過(guò)程。2、RequestBody包含三種類型(類似Content-Type):普通表單,json,文件。
普通表單(默認(rèn)的形式):
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"),其他的文件有對(duì)應(yīng)的格式。
參考地址: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(基礎(chǔ))
cookie在請(qǐng)求的時(shí)候放在請(qǐng)求頭,在返回時(shí)更新cookie
簡(jiǎn)單攜帶方式:
//請(qǐng)求時(shí)傳遞 (返回?cái)?shù)據(jù)時(shí)更新,用sharepreference存)
Request request = new Request.Builder()
.url(url)
.header("Cookie", "xxx")
.build();
-
cookie(自動(dòng)管理)
//下面代碼 實(shí)現(xiàn)自動(dòng)攜帶cookie請(qǐng)求,返回時(shí)自動(dòng)更新
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();