導(dǎo)入
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.7.0'
Get請求
String url = "https://www.baidu.com";
Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "failure: ");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "RESPONSE RESULT:" + response.body().string());
}
});
可以通過header、method設(shè)置更多的參數(shù)
Request request = new Request.Builder()
.url(url)
.header("key","value")
.header("key","value")
.build();
可以通過調(diào)用execute()執(zhí)行同步方法厘唾,當(dāng)然你必須得通過cancel()方法取消褥符。
OkHttp支持大文件下載,如果希望獲得返回的二進(jìn)制字節(jié)數(shù)組抚垃,則調(diào)用response.body().bytes()喷楣;
如果你想拿到返回的inputStream趟大,則調(diào)response.body().byteStream()
final File file = new File(Environment.getExternalStorageDirectory().toString() + "/default.png");
String url = "http://35.185.149.228/static/user/images/default.jpg";;
Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream os = null;
InputStream inputStream = null;
try {
inputStream = response.body().byteStream();
os = new FileOutputStream(file);
while ((len = inputStream.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null)
os.close();
if (inputStream != null)
inputStream.close();
}
}
});
Post請求
post請求創(chuàng)建request和get是一樣的,只是post請求需要提交一個(gè)表單抡蛙,就是RequestBody护昧。
1.普通表單application/x-www-form-urlencoded
String url = "https://www.baidu.com";
FormBody body = new FormBody.Builder()
.add("login_username", "jikexueyuanjgc")
.add("login_password", "123456")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
2.multipart/form-data 上傳文件
File file = new File(Environment.getExternalStorageDirectory() + "/ic_launcher.png");
//不帶參數(shù)的RequestBody
//RequestBody body = RequestBody.create(MediaType.parse("image/png"),file);
//帶參數(shù)的RequestBody
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.addFormDataPart("filename", "testpng");
builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
RequestBody body = builder.build();
3.application/json 數(shù)據(jù)是個(gè)json
RequestBody body = RequestBody.create(MediaType.parse("aaplication/json;charset=utf-8"), "這是你的json串");
自動(dòng)管理Cookie
通過設(shè)置header,上傳Cookie
Request request = new Request.Builder()
.url(url)
.header("Cookie", "xxx")
.build();
通過onRespone獲取Cookie
@Override
public void onResponse(Call call, Response response) throws IOException
{
setCookieList = response.headers("Set-Cookie");
Log.i(TAG, "repose result: " + response.body().string());
}
但是okhttp可以不用我們管理Cookie粗截,自動(dòng)攜帶惋耙,保存和更新Cookie。
方法是在創(chuàng)建OkHttpClient設(shè)置管理Cookie的CookieJar
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();