日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android OkHttp完全解析 是时候来了解OkHttp了

發(fā)布時間:2023/11/30 Android 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android OkHttp完全解析 是时候来了解OkHttp了 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?

Android OkHttp完全解析 是時候來了解OkHttp了

標簽:?AndroidOkHttp ?分類: 【android 進階之路】(67)?

目錄(?)[+]

轉(zhuǎn)載請標明出處:?
http://blog.csdn.net/lmj623565791/article/details/47911083;?
本文出自:【張鴻洋的博客】

一、概述

最近在群里聽到各種討論okhttp的話題,可見okhttp的口碑相當好了。再加上Google貌似在6.0版本里面刪除了HttpClient相關(guān)API,對于這個行為不做評價。為了更好的在應(yīng)對網(wǎng)絡(luò)訪問,學習下okhttp還是蠻必要的,本篇博客首先介紹okhttp的簡單使用,主要包含:

  • 一般的get請求
  • 一般的post請求
  • 基于Http的文件上傳
  • 文件下載
  • 加載圖片
  • 支持請求回調(diào),直接返回對象、對象集合
  • 支持session的保持

最后會對上述幾個功能進行封裝,完整的封裝類的地址見:https://github.com/hongyangAndroid/okhttp-utils

使用前,對于Android?Studio的用戶,可以選擇添加:

compile 'com.squareup.okhttp:okhttp:2.4.0'
  • 1
  • 1

或者Eclipse的用戶,可以下載最新的jar?okhttp he latest JAR?,添加依賴就可以用了。

注意:okhttp內(nèi)部依賴okio,別忘了同時導入okio:

gradle:?compile 'com.squareup.okio:okio:1.5.0'

最新的jar地址:okio the latest JAR


二、使用教程

(一)Http Get

對了網(wǎng)絡(luò)加載庫,那么最常見的肯定就是http get請求了,比如獲取一個網(wǎng)頁的內(nèi)容。

//創(chuàng)建okHttpClient對象 OkHttpClient mOkHttpClient = new OkHttpClient(); //創(chuàng)建一個Request final Request request = new Request.Builder() .url("https://github.com/hongyangAndroid") .build(); //new call Call call = mOkHttpClient.newCall(request); //請求加入調(diào)度 call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(final Response response) throws IOException { //String htmlStr = response.body().string(); } });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 以上就是發(fā)送一個get請求的步驟,首先構(gòu)造一個Request對象,參數(shù)最起碼有個url,當然你可以通過Request.Builder設(shè)置更多的參數(shù)比如:header、method等。

  • 然后通過request的對象去構(gòu)造得到一個Call對象,類似于將你的請求封裝成了任務(wù),既然是任務(wù),就會有execute()和cancel()等方法。

  • 最后,我們希望以異步的方式去執(zhí)行請求,所以我們調(diào)用的是call.enqueue,將call加入調(diào)度隊列,然后等待任務(wù)執(zhí)行完成,我們在Callback中即可得到結(jié)果。

  • 看到這,你會發(fā)現(xiàn),整體的寫法還是比較長的,所以封裝肯定是要做的,不然每個請求這么寫,得累死。

    ok,需要注意幾點:

    • onResponse回調(diào)的參數(shù)是response,一般情況下,比如我們希望獲得返回的字符串,可以通過response.body().string()獲取;如果希望獲得返回的二進制字節(jié)數(shù)組,則調(diào)用response.body().bytes();如果你想拿到返回的inputStream,則調(diào)用response.body().byteStream()

      看到這,你可能會奇怪,竟然還能拿到返回的inputStream,看到這個最起碼能意識到一點,這里支持大文件下載,有inputStream我們就可以通過IO的方式寫文件。不過也說明一個問題,這個onResponse執(zhí)行的線程并不是UI線程。的確是的,如果你希望操作控件,還是需要使用handler等,例如:

      @Override public void onResponse(final Response response) throws IOException { final String res = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { mTv.setText(res); } }); }
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
    • 我們這里是異步的方式去執(zhí)行,當然也支持阻塞的方式,上面我們也說了Call有一個execute()方法,你也可以直接調(diào)用call.execute()通過返回一個Response。

    (二) Http Post 攜帶參數(shù)

    看來上面的簡單的get請求,基本上整個的用法也就掌握了,比如post攜帶參數(shù),也僅僅是Request的構(gòu)造的不同。

    Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null); FormEncodingBuilder builder = new FormEncodingBuilder(); builder.add("username","張鴻洋"); Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); mOkHttpClient.newCall(request).enqueue(new Callback(){});
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    大家都清楚,post的時候,參數(shù)是包含在請求體中的;所以我們通過FormEncodingBuilder。添加多個String鍵值對,然后去構(gòu)造RequestBody,最后完成我們Request的構(gòu)造。

    后面的就和上面一樣了。


    (三)基于Http的文件上傳

    接下來我們在介紹一個可以構(gòu)造RequestBody的Builder,叫做MultipartBuilder。當我們需要做類似于表單上傳的時候,就可以使用它來構(gòu)造我們的requestBody。

    File file = new File(Environment.getExternalStorageDirectory(), "balabala.mp4");RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addPart(Headers.of("Content-Disposition", "form-data; name=\"username\""), RequestBody.create(null, "張鴻洋")) .addPart(Headers.of( "Content-Disposition", "form-data; name=\"mFile\"; filename=\"wjd.mp4\""), fileBody) .build(); Request request = new Request.Builder() .url("http://192.168.1.103:8080/okHttpServer/fileUpload") .post(requestBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { //... });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    上述代碼向服務(wù)器傳遞了一個鍵值對username:張鴻洋和一個文件。我們通過MultipartBuilder的addPart方法可以添加鍵值對或者文件。

    其實類似于我們拼接模擬瀏覽器行為的方式,如果你對這塊不了解,可以參考:從原理角度解析Android (Java) http 文件上傳

    ok,對于我們最開始的目錄還剩下圖片下載,文件下載;這兩個一個是通過回調(diào)的Response拿到byte[]然后decode成圖片;文件下載,就是拿到inputStream做寫文件操作,我們這里就不贅述了。

    關(guān)于用法,也可以參考泡網(wǎng)OkHttp使用教程

    接下來我們主要看如何封裝上述的代碼。


    三、封裝

    由于按照上述的代碼,寫多個請求肯定包含大量的重復代碼,所以我希望封裝后的代碼調(diào)用是這樣的:

    (一)使用

  • 一般的get請求

    OkHttpClientManager.getAsyn("https://www.baidu.com", new OkHttpClientManager.ResultCallback<String>(){@Overridepublic void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(String u) { mTv.setText(u);//注意這里是UI線程 } });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    對于一般的請求,我們希望給個url,然后CallBack里面直接操作控件。

  • 文件上傳且攜帶參數(shù)

    我們希望提供一個方法,傳入url,params,file,callback即可。

    OkHttpClientManager.postAsyn("http://192.168.1.103:8080/okHttpServer/fileUpload",//new OkHttpClientManager.ResultCallback<String>(){@Overridepublic void onError(Request request, IOException e) { e.printStackTrace(); } @Override public void onResponse(String result) { } },// file,// "mFile",// new OkHttpClientManager.Param[]{ new OkHttpClientManager.Param("username", "zhy"), new OkHttpClientManager.Param("password", "123")} );
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    鍵值對沒什么說的,參數(shù)3為file,參數(shù)4為file對應(yīng)的name,這個name不是文件的名字;?
    對應(yīng)于http中的

    <input type="file" name="mFile" >

    對應(yīng)的是name后面的值,即mFile.

  • 文件下載

    對于文件下載,提供url,目標dir,callback即可。

    OkHttpClientManager.downloadAsyn("http://192.168.1.103:8080/okHttpServer/files/messenger_01.png", Environment.getExternalStorageDirectory().getAbsolutePath(), new OkHttpClientManager.ResultCallback<String>(){@Overridepublic void onError(Request request, IOException e) { } @Override public void onResponse(String response) { //文件下載成功,這里回調(diào)的reponse為文件的absolutePath } });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 展示圖片

    展示圖片,我們希望提供一個url和一個imageview,如果下載成功,直接幫我們設(shè)置上即可。

    OkHttpClientManager.displayImage(mImageView, "http://images.csdn.net/20150817/1.jpg");
    • 1
    • 2
    • 1
    • 2

    內(nèi)部會自動根據(jù)imageview的大小自動對圖片進行合適的壓縮。雖然,這里可能不適合一次性加載大量圖片的場景,但是對于app中偶爾有幾個圖片的加載,還是可用的。


  • 四、整合Gson

    很多人提出項目中使用時,服務(wù)端返回的是Json字符串,希望客戶端回調(diào)可以直接拿到對象,于是整合進入了Gson,完善該功能。

    (一)直接回調(diào)對象

    例如現(xiàn)在有個User實體類:

    package com.zhy.utils.http.okhttp;public class User { public String username ; public String password ; public User() { // TODO Auto-generated constructor stub } public User(String username, String password) { this.username = username; this.password = password; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    服務(wù)端返回:

    {"username":"zhy","password":"123"}
    • 1
    • 1

    客戶端可以如下方式調(diào)用:

    OkHttpClientManager.getAsyn("http://192.168.56.1:8080/okHttpServer/user!getUser", new OkHttpClientManager.ResultCallback<User>() {@Overridepublic void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(User user) { mTv.setText(u.toString());//UI線程 } });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    我們傳入泛型User,在onResponse里面直接回調(diào)User對象。?
    這里特別要注意的事,如果在json字符串->實體對象過程中發(fā)生錯誤,程序不會崩潰,onError方法會被回調(diào)。

    注意:這里做了少許的更新,接口命名從StringCallback修改為ResultCallback。接口中的onFailure方法修改為onError。

    (二) 回調(diào)對象集合

    依然是上述的User類,服務(wù)端返回

    [{"username":"zhy","password":"123"},{"username":"lmj","password":"12345"}]
    • 1
    • 1

    則客戶端可以如下調(diào)用:

    OkHttpClientManager.getAsyn("http://192.168.56.1:8080/okHttpServer/user!getUsers", new OkHttpClientManager.ResultCallback<List<User>>() {@Overridepublic void onError(Request request, Exception e) { e.printStackTrace(); } @Override public void onResponse(List<User> us) { Log.e("TAG", us.size() + ""); mTv.setText(us.get(1).toString()); } });
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    唯一的區(qū)別,就是泛型變?yōu)長ist<User>?,ok , 如果發(fā)現(xiàn)bug或者有任何意見歡迎留言。


    源碼

    ok,基本介紹完了,對于封裝的代碼其實也很簡單,我就直接貼出來了,因為也沒什么好介紹的,如果你看完上面的用法,肯定可以看懂:

    package com.zhy.utils.http.okhttp;import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; import android.widget.ImageView; import com.google.gson.Gson; import com.google.gson.internal.$Gson$Types; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.Headers; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.FileNameMap; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created by zhy on 15/8/17. */ public class OkHttpClientManager { private static OkHttpClientManager mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private Gson mGson; private static final String TAG = "OkHttpClientManager"; private OkHttpClientManager() { mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); mGson = new Gson(); } public static OkHttpClientManager getInstance() { if (mInstance == null) { synchronized (OkHttpClientManager.class) { if (mInstance == null) { mInstance = new OkHttpClientManager(); } } } return mInstance; } /** * 同步的Get請求 * * @param url * @return Response */ private Response _getAsyn(String url) throws IOException { final Request request = new Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); Response execute = call.execute(); return execute; } /** * 同步的Get請求 * * @param url * @return 字符串 */ private String _getAsString(String url) throws IOException { Response execute = _getAsyn(url); return execute.body().string(); } /** * 異步的get請求 * * @param url * @param callback */ private void _getAsyn(String url, final ResultCallback callback) { final Request request = new Request.Builder() .url(url) .build(); deliveryResult(callback, request); } /** * 同步的Post請求 * * @param url * @param params post的參數(shù) * @return */ private Response _post(String url, Param... params) throws IOException { Request request = buildPostRequest(url, params); Response response = mOkHttpClient.newCall(request).execute(); return response; } /** * 同步的Post請求 * * @param url * @param params post的參數(shù) * @return 字符串 */ private String _postAsString(String url, Param... params) throws IOException { Response response = _post(url, params); return response.body().string(); } /** * 異步的post請求 * * @param url * @param callback * @param params */ private void _postAsyn(String url, final ResultCallback callback, Param... params) { Request request = buildPostRequest(url, params); deliveryResult(callback, request); } /** * 異步的post請求 * * @param url * @param callback * @param params */ private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params) { Param[] paramsArr = map2Params(params); Request request = buildPostRequest(url, paramsArr); deliveryResult(callback, request); } /** * 同步基于post的文件上傳 * * @param params * @return */ private Response _post(String url, File[] files, String[] fileKeys, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, params); return mOkHttpClient.newCall(request).execute(); } private Response _post(String url, File file, String fileKey) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null); return mOkHttpClient.newCall(request).execute(); } private Response _post(String url, File file, String fileKey, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params); return mOkHttpClient.newCall(request).execute(); } /** * 異步基于post的文件上傳 * * @param url * @param callback * @param files * @param fileKeys * @throws IOException */ private void _postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, params); deliveryResult(callback, request); } /** * 異步基于post的文件上傳,單文件不帶參數(shù)上傳 * * @param url * @param callback * @param file * @param fileKey * @throws IOException */ private void _postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null); deliveryResult(callback, request); } /** * 異步基于post的文件上傳,單文件且攜帶其他form參數(shù)上傳 * * @param url * @param callback * @param file * @param fileKey * @param params * @throws IOException */ private void _postAsyn(String url, ResultCallback callback, File file, String fileKey, Param... params) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params); deliveryResult(callback, request); } /** * 異步下載文件 * * @param url * @param destFileDir 本地文件存儲的文件夾 * @param callback */ private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) { final Request request = new Request.Builder() .url(url) .build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { sendFailedStringCallback(request, e, callback); } @Override public void onResponse(Response response) { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //如果下載文件成功,第一個參數(shù)為文件的絕對路徑 sendSuccessResultCallback(file.getAbsolutePath(), callback); } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } private String getFileName(String path) { int separatorIndex = path.lastIndexOf("/"); return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length()); } /** * 加載圖片 * * @param view * @param url * @throws IOException */ private void _displayImage(final ImageView view, final String url, final

    轉(zhuǎn)載于:https://www.cnblogs.com/xgjblog/p/6007052.html

    總結(jié)

    以上是生活随笔為你收集整理的Android OkHttp完全解析 是时候来了解OkHttp了的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。