咱們知道在Android開發中是能夠直接使用現成的API進行網絡請求的,就是使用 HttpClient 和 HttpURLConnention ,而Android 4.4 以後 HttpClient 已經被廢棄,因爲此前一直很流行的三方庫 android-async-http 是基於 HttpClient 的,因此做者已經放棄了維護 android-async-http 庫,咱們在項目中也儘可能不要使用這個庫。android
OkHttp是Squaur公司開源的一個高性能Http請求庫,它的職責同 HttpURLConnention 是同樣的,支持SDPY、Http 2.0、websocket,支持同步、異步,並且OkHttp又封裝了線程池、數據轉換、參數使用、錯誤處理等,API使用起來更加方便。git
這裏首先簡單的介紹一下最新版 OkHttp 3.4.1 的使用以及對於同步GET和POST請求的簡單封裝,後續會補上異步GET和PST請求、源碼解析等內容。github
下面代碼封裝了兩個使用OkHttp同步GET、POST請求網絡的API,服務器返回來的都是JSON格式的字符串,而對於POST請求,客戶端提交上去的也是JSON格式的字符串,源碼以下:web
/** * Created by stevewang on 2016/7/28. */ public class OkHttpUtils { private static final OkHttpClient mClient = new OkHttpClient(); public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); /** * GET方式同步請求網絡,服務器端返回JSON格式的響應 * * @param urlString * @return * @throws IOException */ public static String getStringFromURL(String urlString) throws IOException { // 1. 獲取Request對象 Request request = new Request.Builder() .url(urlString) .build(); // 2. 獲取Call對象 Call call = mClient.newCall(request); // 3. 調用同步請求方法execute(),獲取Response對象, Response response = call.execute(); // 4. 獲取ResponseBody對象 ResponseBody responseBody = response.body(); if(responseBody != null) { // 5. 從ResponseBody對象中取出服務器端返回數據 return responseBody.string(); } return null; } /** * POST方式同步請求網絡,向服務器端提交JSON格式的請求,服務器端返回JSON格式的響應 * * @param urlString * @param jsonRequest * @return * @throws IOException */ public static String postJsonToURL(String urlString, String jsonRequest) throws IOException { // 1. 首先構造RequestBody對象,指定了MediaType爲JSON,這一步是POST請求與GET請求的主要區別 RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonRequest); // 2. 獲取Request對象,將RequestBody放置到Request對象中 Request request = new Request.Builder() .url(urlString) // .addHeader(name, value) // 添加請求頭 .post(requestBody) .build(); // 3. 獲取Call對象 Call call = mClient.newCall(request); // 4. 調用同步請求方法execute(),獲取Response對象, Response response = call.execute(); // 5. 獲取ResponseBody對象 ResponseBody responseBody = response.body(); if(responseBody != null) { // 6. 從ResponseBody對象中取出服務器端返回數據 return responseBody.string(); } return null; } }