一、OKHttp3簡介
OKHttp是一個處理網絡請求的輕量級開源框架,由移動支付Square公司貢獻,用於替代HttpUriConnection和Apache HTTPClient,進行http請求,從Android 4.4 開始HttpUrlConnection底層實現採用OKHttp,而HttpClient已經廢棄,並且在Android 6.0 API 23 後已被移除。
GitHub:https://github.com/square/okhttp(截止到博客更新時已有 27096 Star)
http://square.github.io/okhttp/
OKHttp功能:
- post,get等請求
- 文件上傳下載
- 加載圖片
- 支持請求回調,直接返回對象、對象集合
- 支持session的保持
OKHttp優點:
- 支持HTTP2/SPDY(SPDY是Google開發的基於TCP的傳輸層協議,用以最小化網絡延遲,提升網絡速度,優化用戶的網絡使用體驗)
- socket自動選擇路線,支持重連,擁有自動維護的socket連接池,減少握手次數,減少了請求延遲,共享socket,減少了對服務器的請求次數
- 基於Headers的緩存策略減少重複的網路請求
- 擁有Interceptors輕鬆處理請求與相應(自動處理GZip壓縮)
當然還有很多其他主流框架,每個框架的優缺點不同,應當根據需求選擇合適的框架,比如Google推出的Volley,對頻繁的、數據量小的網絡請求表現較好,而不適合處理大數據量的操作(比如下載文件),Retrofit基於註解,專注於接口封裝,相比之下OKHttp性能較高使用靈活,同時也需要我們自己再進行一層封裝。
二、OKHttp3使用
首先要添加OKHttp3的依賴
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okio:okio:1.14.0'
以登錄爲例,post方法使用如下
public static String login(String url, String sid, String password) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("sid", sid)
.add("password", password)
.build();
Log.d("FormBody", formBody.toString());
Request request = new Request.Builder()
.url(url+"/login")
.post(formBody)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
同樣get方法形式如下
public static String get(String url) throws IOException{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
需要注意的是,url前面必須包含 http://,後面跟冒號和端口號
三、OKHttp3下載和上傳圖片
使用get方法下載圖片,返回byte數組
/**
* 下載圖片
* @param url
* @param imagePath 圖片路徑
* @return byte[]
* @throws IOException
*/
public static byte[] downloadImage(String url, String imagePath) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url+"/show?fileName="+imagePath)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = response.body().bytes();
return bytes;
}
使用post方法上傳圖片
/**
* 上傳圖片
* @param url
* @param imagePath 圖片路徑
* @return 新圖片的路徑
* @throws IOException
* @throws JSONException
*/
public static String uploadImage(String url, String imagePath) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
Log.d("imagePath", imagePath);
File file = new File(imagePath);
RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", imagePath, image)
.build();
Request request = new Request.Builder()
.url(url+"/uploadImage")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.optString("image");
}