OkHttp使用介紹

爲何須要一個HTTP庫

Android系統提供了兩種HTTP通訊類,HttpURLConnection和HttpClient。
關於HttpURLConnection和HttpClient的選擇>>官方博客
儘管Google在大部分安卓版本中推薦使用HttpURLConnection,可是這個類相比HttpClient實在是太難用,太弱爆了。
OkHttp是一個相對成熟的解決方案,聽說Android4.4的源碼中能夠看到HttpURLConnection已經替換成OkHttp實現了。因此咱們更有理由相信OkHttp的強大。html

入門

官方資料

官方介紹
github源碼java

使用範圍

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

jar包準備

官方介紹頁面有連接位置。這裏把下載連接也寫在下面。
OkHttp
Okiogit

基本使用

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中的響應。github

Response類:

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);
    }
}

 

response.body()返回ResponseBody類

能夠方便的獲取stringapache

public final String string() throws IOException
Returns 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

 

固然也能獲取到流的形式:json

public final InputStream byteStream()

 

HTTP POST

POST提交Json數據

 

使用Request的post方法來提交請求體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在不少時候使用都是很方便的,並且不少代碼也有重複,所以特意整理了下面的工具類。
注意:異步

  • 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 github官方教程進行了翻譯。
請看個人另外一篇博客:OkHttp使用進階 譯自OkHttp Github官方教程

相關文章
相關標籤/搜索