一, OKHttp介紹
okhttp是一個(gè)第三方類庫(kù),用于android中請(qǐng)求網(wǎng)絡(luò)。
這是一個(gè)開(kāi)源項(xiàng)目,是安卓端最火熱的輕量級(jí)框架,由移動(dòng)支付Square公司貢獻(xiàn)(該公司還貢獻(xiàn)了Picasso和LeakCanary) 。
用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。
okhttp有自己的官網(wǎng),官網(wǎng)網(wǎng)址:[OKHttp官網(wǎng)](http://square.github.io/okhttp/)
如果想了解原碼可以在github上下載,地址是:[https://github.com/square/okhttp](https://github.com/square/okhttp)
在AndroidStudio中使用不需要下載jar包,直接添加依賴即可:
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
二、使用
OkHttp3開(kāi)發(fā)三部曲:
1、創(chuàng)建OkHttpClient,添加配置
2、創(chuàng)建請(qǐng)求
3、執(zhí)行請(qǐng)求
下面分別來(lái)說(shuō)說(shuō)這三個(gè)步驟:
1. 創(chuàng)建OkHttpClient
一個(gè)最簡(jiǎn)單的OkHttpClient
OkHttpClient okHttpClient=new OkHttpClient.Builder().build();
一個(gè)復(fù)雜點(diǎn)的OkHttpClient配置
File cacheDir = new File(getCacheDir(), "okhttp_cache");
//File cacheDir = new File(getExternalCacheDir(), "okhttp");
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5*1000, TimeUnit.MILLISECONDS) //鏈接超時(shí)
.readTimeout(10*1000,TimeUnit.MILLISECONDS) //讀取超時(shí)
.writeTimeout(10*1000,TimeUnit.MILLISECONDS) //寫入超時(shí)
.addInterceptor(new HttpHeadInterceptor()) //應(yīng)用攔截器:統(tǒng)一添加消息頭
.addNetworkInterceptor(new NetworkspaceInterceptor())//網(wǎng)絡(luò)攔截器
.addInterceptor(loggingInterceptor)//應(yīng)用攔截器:打印日志
.cache(cache) //設(shè)置緩存
.build();
具體可配置參數(shù)見(jiàn)OkHttpClient.Builder類,幾點(diǎn)注意事項(xiàng):
1.攔截器
兩種攔截器:Interceptor(應(yīng)用攔截器)、NetworkInterceptor(網(wǎng)絡(luò)攔截器)
1)Interceptor比NetworkInterceptor先執(zhí)行
2)同一種Interceptor倒序返回
A(start)----B(start)----B(end)----A(end)
因此上面配置的Interceptor執(zhí)行順序如下
HttpHeadInterceptor start----LoggingInterceptor start----LoggingInterceptor end---HttpHeadInterceptor end
3)日志攔截器
自定義日志攔截器
public class LoggingInterceptor implements Interceptor {
private static final String TAG="Okhttp";
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d(TAG,String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d(TAG,String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.d(TAG,content);
response=response.newBuilder()
.body(ResponseBody.create(mediaType,content))
.build();
return response;
}
}
官方提供的Logging Interceptor
地址:https://github.com/victorfan336/okhttp-logging-interceptor
gradle.build中添加依賴:
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
使用方法
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BODY);//日志級(jí)別,Body級(jí)別打印的信息最全面
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
2、注意
開(kāi)發(fā)中應(yīng)該只維護(hù)一個(gè)OkHttpClient實(shí)例,這樣可以復(fù)用連接池、線程池等,避免性能開(kāi)銷
如果想修改參數(shù),可通過(guò)
okHttpClient.newBuilder()修改,這樣可以復(fù)用okHttpClient之前的所有配置,
比如想針對(duì)某個(gè)請(qǐng)求修改鏈接超時(shí)。
OkHttpClient newClient=okHttpClient.newBuilder()
.connectTimeout(10*1000,TimeUnit.MILLISECONDS)
.build();
newClient.newCall(req);
二、創(chuàng)建請(qǐng)求
GET請(qǐng)求
通過(guò)Request.Builder創(chuàng)建請(qǐng)求,默認(rèn)是Get請(qǐng)求
Request req = new Request.Builder().url(url).build();
Call call = okHttpClient.newCall(req);
POST請(qǐng)求
主要是構(gòu)建RequestBody,并設(shè)置Content-Type消息頭。
1.普通Post請(qǐng)求
比如json請(qǐng)求
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
Request req = new Request.Builder().url(url)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(req);
2. 使用FormBody傳遞鍵值對(duì)參數(shù)
Content-Type: application/x-www-form-urlencoded
比如:
RequestBody requestBody =
new FormBody.Builder()
.add("username", "zhangsan")
.add("password", "1111111")
.build();
Request req = new Request.Builder().url(url).post(uploadBody).build();
Call call = okHttpClient.newCall(req);
3. 使用RequestBody傳遞Json或File對(duì)象
RequestBody是抽象類,故不能直接使用,但是他有靜態(tài)方法create,使用這個(gè)方法可以得到RequestBody對(duì)象。
這種方式可以上傳Json對(duì)象或File對(duì)象。
上傳json對(duì)象使用示例如下:
OkHttpClient client = new OkHttpClient();//創(chuàng)建OkHttpClient對(duì)象。
MediaType JSON = MediaType.parse("application/json; charset=utf-8");//數(shù)據(jù)類型為json格式,
String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json數(shù)據(jù).
RequestBody body = RequestBody.create(JSON, josnStr);
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
...
});//此處省略回調(diào)方法。
上傳File對(duì)象使用示例如下:
OkHttpClient client = new OkHttpClient();//創(chuàng)建OkHttpClient對(duì)象。
MediaType fileType = MediaType.parse("File/*");//數(shù)據(jù)類型為json格式,
File file = new File("path");//file對(duì)象.
RequestBody body = RequestBody.create(fileType , file );
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {。。。});//此處省略回調(diào)方法。
4. 使用MultipartBody同時(shí)傳遞鍵值對(duì)參數(shù)和File對(duì)象
這個(gè)字面意思是多重的body。我們知道FromBody傳遞的是字符串型的鍵值對(duì),RequestBody傳遞的是多媒體,那么如果我們想二者都傳遞怎么辦?
此時(shí)就需要使用MultipartBody類。
使用示例如下:
OkHttpClient client = new OkHttpClient();
MultipartBody multipartBody =new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("groupId",""+groupId)//添加鍵值對(duì)參數(shù)
.addFormDataPart("title","title")
.addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件
.build();
final Request request = new Request.Builder()
.url(URLContant.CHAT_ROOM_SUBJECT_IMAGE)
.post(multipartBody)
.build();
client.newCall(request).enqueue(new Callback() {。。。});
Request req = new Request.Builder().url(url).post(uploadBody).build();
okHttpClient.newCall(req);
5. 使用MultipartBody提交分塊請(qǐng)求
MultipartBody 可以構(gòu)建復(fù)雜的請(qǐng)求體,與HTML文件上傳形式兼容。
多塊請(qǐng)求體中每塊請(qǐng)求都是一個(gè)請(qǐng)求體,可以定義自己的請(qǐng)求頭,這些請(qǐng)求頭可以用來(lái)描述這塊請(qǐng)求。
例如他的Content-Disposition。如果Content-Length和Content-Type可用的話,他們會(huì)被自動(dòng)添加到請(qǐng)求頭中。
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void postMultipartBody() {
OkHttpClient client = new OkHttpClient();
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
MultipartBody body = new MultipartBody.Builder("AaB03x")
.setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(body)
.build();
Call call = client.newCall(request);
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.body().string());
}
});
}
6. 自定義RequestBody實(shí)現(xiàn)流的上傳
在上面的分析中我們知道,只要是RequestBody類以及子類都可以作為post方法的參數(shù),下面我們就自定義一個(gè)類,繼承RequestBody,實(shí)現(xiàn)流的上傳。
使用示例如下:
首先創(chuàng)建一個(gè)RequestBody類的子類對(duì)象:
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {//重寫writeTo方法
FileInputStream fio= new FileInputStream(new File("fileName"));
byte[] buffer = new byte[1024*8];
if(fio.read(buffer) != -1){
sink.write(buffer);
}
}
};
然后使用body對(duì)象:
OkHttpClient client = new OkHttpClient();//創(chuàng)建OkHttpClient對(duì)象。
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {。。。});
以上代碼的與眾不同就是body對(duì)象,這個(gè)body對(duì)象重寫了write方法,里面有個(gè)sink對(duì)象。這個(gè)是OKio包中的輸出流,有write方法。使用這個(gè)方法我們可以實(shí)現(xiàn)上傳流的功能。
使用RequestBody上傳文件時(shí),并沒(méi)有實(shí)現(xiàn)斷點(diǎn)續(xù)傳的功能。我可以使用這種方法結(jié)合RandomAccessFile類實(shí)現(xiàn)斷點(diǎn)續(xù)傳的功能。
三、執(zhí)行請(qǐng)求
1、同步執(zhí)行
Response response = call.execute();
由于android強(qiáng)制要求網(wǎng)絡(luò)請(qǐng)求在線程中執(zhí)行,所以無(wú)法使用execute
2、異步執(zhí)行
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失敗回調(diào)
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//成功回調(diào),當(dāng)前線程為子線程,如果需要更新UI,需要post到主線程中
boolean successful = response.isSuccessful();
//響應(yīng)消息頭
Headers headers = response.headers();
//響應(yīng)消息體
ResponseBody body = response.body();
String content=response.body().string());
//緩存控制
CacheControl cacheControl = response.cacheControl();
}
});
1)Response:封裝了網(wǎng)絡(luò)響應(yīng)消息,比如響應(yīng)消息頭、緩存控制、響應(yīng)消息體等。
String content=response.body().string(); //獲取字符串
InputStream inputStream = response.body().byteStream();//獲取字節(jié)流(比如下載文件)
2)Callback回調(diào)是在子線程中執(zhí)行的,如果要更新UI,請(qǐng)post到主線程中。
三、其他設(shè)置
1. 設(shè)置請(qǐng)求頭
OKHttp中設(shè)置請(qǐng)求頭特別簡(jiǎn)單,在創(chuàng)建request對(duì)象時(shí)調(diào)用一個(gè)方法即可。
使用示例如下:
Request request = new Request.Builder()
.url("http://www.baidu.com")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("token", "myToken")
.build();
2. 設(shè)置超時(shí)
沒(méi)有響應(yīng)時(shí)使用超時(shí)結(jié)束call。沒(méi)有響應(yīng)的原因可能是客戶點(diǎn)鏈接問(wèn)題、服務(wù)器可用性問(wèn)題或者這之間的其他東西。OkHttp支持連接,讀取和寫入超時(shí)。
Request request = new Request.Builder()
.url("http://www.baidu.com")
.connectTimeout(10, TimeUnit.SECONDS);//連接超時(shí)
.readTimeout(10,TimeUnit.SECONDS);//讀取超時(shí)
.writeTimeout(10,TimeUnit.SECONDS);//寫入超時(shí)
.build();
3. 設(shè)置緩存
為了緩存響應(yīng),你需要一個(gè)你可以讀寫的緩存目錄,和緩存大小的限制。這個(gè)緩存目錄應(yīng)該是私有的,不信任的程序應(yīng)不能讀取緩存內(nèi)容。
一個(gè)緩存目錄同時(shí)擁有多個(gè)緩存訪問(wèn)是錯(cuò)誤的。大多數(shù)程序只需要調(diào)用一次new OkHttpClient(),在第一次調(diào)用時(shí)配置好緩存,然后其他地方只需要調(diào)用這個(gè)實(shí)例就可以了。否則兩個(gè)緩存示例互相干擾,破壞響應(yīng)緩存,而且有可能會(huì)導(dǎo)致程序崩潰。
響應(yīng)緩存使用HTTP頭作為配置。你可以在請(qǐng)求頭中添加Cache-Control: max-stale=3600 ,OkHttp緩存會(huì)支持。你的服務(wù)通過(guò)響應(yīng)頭確定響應(yīng)緩存多長(zhǎng)時(shí)間,例如使用Cache-Control: max-age=9600。
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cache(cache);
OkHttpClient client = builder.build();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
...
});
Okhttp使用上的一些缺點(diǎn)
1、對(duì)于Get請(qǐng)求,如果請(qǐng)求參數(shù)較多,自己拼接Url較為麻煩
比如
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("http")
.host("www.baidu.com")
.addPathSegment("user")
.addPathSegment("login")
.addQueryParameter("username", "zhangsan")
.addQueryParameter("password","123456")
.build();
拼接結(jié)果:http://www.baidu.com/user/login/username=zhangsan&password=123456
如果能做一些封裝,直接addParam(key,value)的形式則會(huì)簡(jiǎn)單很多。
2、Callback在子線程中回調(diào),大部分時(shí)候,我們都是需要更新UI的,還需自己post到主線程中處理。
3、構(gòu)建請(qǐng)求步驟比較多
因此,Square提供了針對(duì)OkHttp的封裝庫(kù)Retrofit,另外Github上也有很多第三方的封裝庫(kù),比如OkGo。