1.使用前準備android
Android Studio 配置gradle:git
compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.okio:okio:1.7.0'
添加網絡權限:github
<uses-permission android:name="android.permission.INTERNET"/>
2.異步GET請求編程
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.異步POST請求api
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(); } }); } }); }
3.異步上傳文件服務器
上傳文件自己也是一個POST請求,上一篇沒有講,這裏咱們補上。首先定義上傳文件類型:markdown
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文件中的內容 :異步
這裏寫圖片描述
固然不要忘了添加以下權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
4.異步下載文件
下載文件一樣在上一篇沒有講到,實現起來比較簡單,在這裏下載一張圖片,咱們獲得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", "文件下載成功"); } });
}
5.異步上傳Multipart文件
這種場景很經常使用,咱們有時會上傳文件同時還須要傳其餘類型的字段,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()); } }); }
6.設置超時時間和緩存
和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();
7.關於取消請求和封裝
OkHttpFinal,它目前是基於OkHttp3來進行封裝的。連接描述
8.關於源碼Demo
github源碼下載連接描述