国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android OkHttp基本使用詳解

2019-10-22 18:13:53
字體:
來源:轉載
供稿:網友

Android系統提供了兩種HTTP通信類,HttpURLConnectionHttpClient

盡管Google在大部分安卓版本中推薦使用HttpURLConnection,但是這個類相比HttpClient實在是太難用,太弱爆了。

OkHttp是一個相對成熟的解決方案,據說Android4.4的源碼中可以看到HttpURLConnection已經替換成OkHttp實現了。所以我們更有理由相信OkHttp的強大。

使用范圍

OkHttp支持Android 2.3及其以上版本。
對于Java, JDK1.7以上。

基本使用

HTTP GET

OkHttpClient client = new OkHttpClient();String run(String url) throws IOException {  Request request = new Request.Builder().url(url).build();  Response response = client.newCall(request).execute();  if (response.isSuccessful()) {    return response.body().string();  } else {    throw new IOException("Unexpected code " + response);  }}

Request是OkHttp中訪問的請求,Builder是輔助類。Response即OkHttp中的響應。

Response類:

public boolean isSuccessful()Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

response.body()返回ResponseBody

可以方便的獲取string

public final String string() throws IOExceptionReturns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.Throws:IOException

當然也能獲取到流的形式:

public final InputStream byteStream()

HTTP POST

POST提交Json數據

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {  RequestBody body = RequestBody.create(JSON, json);  Request request = new Request.Builder()   .url(url)   .post(body)   .build();  Response response = client.newCall(request).execute();  f (response.isSuccessful()) {    return response.body().string();  } else {    throw new IOException("Unexpected code " + response);  }}

使用Requestpost方法來提交請求體RequestBody

POST提交鍵值對

很多時候我們會需要通過POST方式把鍵值對數據傳送到服務器。 OkHttp提供了很方便的方式來做這件事情。

OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {  RequestBody formBody = new FormEncodingBuilder()  .add("platform", "android")  .add("name", "bug")  .add("subject", "XXXXXXXXXXXXXXX")  .build();  Request request = new Request.Builder()   .url(url)   .post(body)   .build();  Response response = client.newCall(request).execute();  if (response.isSuccessful()) {    return response.body().string();  } else {    throw new IOException("Unexpected code " + response);  }}

注意:

  • OkHttp官方文檔并不建議我們創建多個OkHttpClient,因此全局使用一個。 如果有需要,可以使用clone方法,再進行自定義。這點在后面的高級教程里會提到。
  • enqueue為OkHttp提供的異步方法,入門教程中并沒有提到,后面的高級教程里會有解釋。
import java.io.IOException;import java.util.List;import java.util.concurrent.TimeUnit;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.message.BasicNameValuePair;import cn.wiz.sdk.constant.WizConstant;import com.squareup.okhttp.Callback;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;  public class OkHttpUtil {  private static final OkHttpClient mOkHttpClient = new OkHttpClient();  static{    mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);  }  /**   * 該不會開啟異步線程。   * @param request   * @return   * @throws IOException   */  public static Response execute(Request request) throws IOException{    return mOkHttpClient.newCall(request).execute();  }  /**   * 開啟異步線程訪問網絡   * @param request   * @param responseCallback   */  public static void enqueue(Request request, Callback responseCallback){    mOkHttpClient.newCall(request).enqueue(responseCallback);  }  /**   * 開啟異步線程訪問網絡, 且不在意返回結果(實現空callback)   * @param request   */  public static void enqueue(Request request){    mOkHttpClient.newCall(request).enqueue(new Callback() {            @Override      public void onResponse(Response arg0) throws IOException {              }            @Override      public void onFailure(Request arg0, IOException arg1) {              }    });  }  public static String getStringFromServer(String url) throws IOException{    Request request = new Request.Builder().url(url).build();    Response response = execute(request);    if (response.isSuccessful()) {      String responseUrl = response.body().string();      return responseUrl;    } else {      throw new IOException("Unexpected code " + response);    }  }  private static final String CHARSET_NAME = "UTF-8";  /**   * 這里使用了HttpClinet的API。只是為了方便   * @param params   * @return   */  public static String formatParams(List<BasicNameValuePair> params){    return URLEncodedUtils.format(params, CHARSET_NAME);  }  /**   * 為HttpGet 的 url 方便的添加多個name value 參數。   * @param url   * @param params   * @return   */  public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){    return url + "?" + formatParams(params);  }  /**   * 為HttpGet 的 url 方便的添加1個name value 參數。   * @param url   * @param name   * @param value   * @return   */  public static String attachHttpGetParam(String url, String name, String value){    return url + "?" + name + "=" + value;  }}

總結

通過上面的例子我們可以發現,OkHttp在很多時候使用都是很方便的,而且很多代碼也有重復,因此特地整理了下面的工具類。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建水县| 扎囊县| 南京市| 赤水市| 广安市| 铜川市| 金湖县| 翁牛特旗| 南溪县| 武乡县| 荆门市| 吴江市| 城市| 锦州市| 连城县| 乐清市| 凤山市| 沂源县| 红原县| 柏乡县| 安仁县| 惠水县| 陇川县| 普格县| 马龙县| 康乐县| 麻江县| 罗甸县| 建平县| 长阳| 犍为县| 桓台县| 沐川县| 宜兰县| 郁南县| 乌苏市| 红安县| 建瓯市| 海安县| 班戈县| 常德市|