OKHttp是一個處理網絡請求的框架,其優勢有,支持http2,對一臺機器的全部請求共享同一個socket。json
內置鏈接池,支持鏈接複用,減小延遲。經過緩存避免重複的請求,請求失敗時自動重試主機的其餘ip,自動重定向。 緩存
compile 'com.squareup.okhttp3:okhttp:3.8.1'
OkHttpClient okHttpClient; Request request; okHttpClient = new OkHttpClient(); request = new Request.Builder() .url("http://www.baidu.com")//請求接口,若是須要傳參拼接到接口後面,如www.baidu.com?name=zhangsan&sex=18 .build(); final Call call = okHttpClient.newCall(request); new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute();//獲得Response 對象 if(response.isSuccessful()){//判斷是否響應 Log.d("response ","響應碼"+response.code());//返回http協議的響應碼 Log.d("response ","返回內容"+response.body().string()); } } catch (IOException e) { e.printStackTrace(); } } });
OkHttpClient okHttpClient; Request request; okHttpClient = new OkHttpClient(); request = new Request.Builder() .url("http://www.baidu.com")//請求接口。若是須要傳參拼接到接口後面,如www.baidu.com?name=zhangsan&sex=18 .build(); final Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){//判斷是否響應 Log.d("response ","響應碼"+response.code());//返回http協議的響應碼 Log.d("response ","返回內容"+response.body().string()); } } });
FormBody body = new FormBody.Builder() //建立信息主體 .add("name", name) .add("sex", department) .add("possword", post) .add("data", formatter.format(getData())) .build();
//傳遞Json對象 MediaType JSON = MediaType.parse("application/json; charset=utf-8");//指定數據類型爲json對象, String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json數據. RequestBody body = RequestBody.create(JSON, josnStr); //傳遞File對象 MediaType fileType = MediaType.parse("File/*");//指定數據類型爲file對象, File file = new File(path);//file對象 RequestBody body = RequestBody.create(fileType , file );
MultipartBody multipartBody =new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("groupId",""+Id)//添加鍵值對參數 .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件 .build();
//FormBody傳遞數據,Post同步請求 OkHttpClient okHttpClient; okHttpClient = new OkHttpClient(); FormBody body = new FormBody.Builder() //建立信息主體 .add("name", name) .add("sex", department) .add("possword", post) .add("data", formatter.format(getData())) .build(); Request requset = new Request.Builder() .url("url") .post(body) .build(); final Call call = okHttpClient.newCall(requset); new Thread(new Runnable() { @Override public void run() { try { Response response = call3.execute();//獲得Response 對象 if(response.isSuccessful()){//判斷是否響應 Log.d("response ","響應碼"+response.code());//返回http協議的響應碼 Log.d("response ","返回內容"+response.body().string()); } } catch (IOException e) { e.printStackTrace(); } } }); //RequestBody()傳遞數據,Post異步請求 OkHttpClient okHttpClient; okHttpClient = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8");//數據類型爲json格式, String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json數據. RequestBody body = RequestBody.create(JSON, jsonStr); Request request = new Request.Builder() .url("http://www.baidu.com") .post(body) .build(); final Call call = okHttpClient.newCall(requset); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){//判斷是否響應 Log.d("response ","響應碼"+response.code());//返回http協議的響應碼 Log.d("response ","返回內容"+response.body().string()); } } });
經過上述代碼,Get或Post請求須要實例化OkHttpClient對象,用Request建立請求和Response發送請求,以及Call調度器接收返回內容。網絡
Call對象有兩種模式,call.excute()同步模式,call.enqueue()異步模式。app
同步是在主線程操做,因此須要開啓子線程操做。異步是CallBack回調回來的Response,是在子線程操做,可是回調的onFailure()和onResponse()依然在子線程中。框架
respinse.body() 也是在子線程,須要接收到內容,才能調用主線程操做。異步
注意response.body()只能調用一次,由於是輸出流的讀操做,而讀寫操做只接收一次,第二次會返回null。socket
OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS)//設置超時時間 .readTimeout(10, TimeUnit.SECONDS)//設置讀取超時時間 .writeTimeout(10, TimeUnit.SECONDS);//設置寫入超時時間