編輯:關於Android編程
上一篇介紹了OkHttp2.x的用法,這一篇文章我們來對照OkHttp2.x版本來看看,OkHttp3使用起來有那些變化。
Android Studio 配置gradle:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.7.0'
添加網絡權限:
慣例,請求百度:
private void getAsynHttp() {
mOkHttpClient=new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");
//可以省略,默認是GET請求
requestBuilder.method("GET",null);
Request request = requestBuilder.build();
Call mcall= mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response.cacheResponse()) {
String str = response.cacheResponse().toString();
Log.i("wangshu", "cache---" + str);
} else {
response.body().string();
String str = response.networkResponse().toString();
Log.i("wangshu", "network---" + str);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "請求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
與2.x版本並沒有什麼不同,比較郁悶的是回調仍然不在UI線程。
OkHttp3異步POST請求和OkHttp2.x有一些差別就是沒有FormEncodingBuilder這個類,替代它的是功能更加強大的FormBody:
private void postAsynHttp() {
mOkHttpClient=new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("size", "10")
.build();
Request request = new Request.Builder()
.url("http://api.1-blog.com/biz/bizserver/article/list.do")
.post(formBody)
.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 {
String str = response.body().string();
Log.i("wangshu", str);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "請求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
上傳文件本身也是一個POST請求,上一篇沒有講,這裡我們補上。首先定義上傳文件類型:
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
將sdcard根目錄的wangshu.txt文件上傳到服務器上:
private void postAsynFile() {
mOkHttpClient=new OkHttpClient();
File file = new File("/sdcard/wangshu.txt");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("wangshu",response.body().string());
}
});
}
當然如果想要改為同步的上傳文件只要調用 mOkHttpClient.newCall(request).execute()就可以了。
在wangshu.txt文件中有一行字“Android網絡編程(六)OkHttp3用法全解析”我們運行程序點擊發送文件按鈕,最終請求網絡返回的結果就是我們txt文件中的內容 :
當然不要忘了添加如下權限:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;">
下載文件同樣在上一篇沒有講到,實現起來比較簡單,在這裡下載一張圖片,我們得到Response後將流寫進我們指定的圖片文件中就可以了。
private void downAsynFile() {
mOkHttpClient = new OkHttpClient();
String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
} catch (IOException e) {
Log.i("wangshu", "IOException");
e.printStackTrace();
}
Log.d("wangshu", "文件下載成功");
}
});
}
這種場景很常用,我們有時會上傳文件同時還需要傳其他類型的字段,OkHttp3實現起來很簡單,需要注意的是沒有服務器接收我這個Multipart文件,所以這裡只是舉個例子,具體的應用還要結合實際工作中對應的服務器。
首先定義上傳文件類型:
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void sendMultipart(){
mOkHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "wangshu")
.addFormDataPart("image", "wangshu.jpg",
RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + "...")
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("wangshu", response.body().string());
}
});
}
和OkHttp2.x有區別的是不能通過OkHttpClient直接設置超時時間和緩存了,而是通過OkHttpClient.Builder來設置,通過builder配置好OkHttpClient後用builder.build()來返回OkHttpClient,所以我們通常不會調用new OkHttpClient()來得到OkHttpClient,而是通過builder.build():
File sdcache = getExternalCacheDir();
int cacheSize = 10 * 1024 * 1024;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
OkHttpClient mOkHttpClient=builder.build();
取消請求仍舊可以調用call.cancel(),這個沒有變化,不明白的可以查看上一篇文章Android網絡編程(五)OkHttp2.x用法全解析,這裡就不贅述了,封裝上一篇也講過仍舊推薦OkHttpFinal,它目前是基於OkHttp3來進行封裝的。
源碼Demo很簡單就四個按鈕用來測試上面講到的內容:
github源碼下載
URL(Uniform Resource Locator)對象代表統一資源定位器,它是指向互聯網資源的指針。URL由協議名、主機、端口和資源路徑組件,即滿足
前言:為什麼要了解系統Activity,Service,,BroadCastReceiver,ContentProvider的啟動流程,這是一個對於即將理解插件中的四大組
在網上查了好多資料,大致都雷同,大家都是互相抄襲的,看著很費勁,不好理解,自己總結一下,留著需要看的話來查找。代碼中的例子如下:復制代碼 代碼如下:<ImageVi
概述作為一個android開發者,在開發應用時,隨著業務規模發展到一定程度,不斷地加入新功能、添加新的類庫,代碼在急劇的膨脹,相應的apk包的大小也急劇增加,