概述 OKhttp是一個網路請求開源項目,Android網路請求輕量級框架,支持文件上傳與下載,支持https,由移動支付Square公司貢獻。 依賴 Get請求 Get方式發送同步請求 Get方式發送非同步請求 Post請求 FormBody傳遞鍵值對參數 RequestBody傳遞Json或Fil ...
概述
OKhttp是一個網路請求開源項目,Android網路請求輕量級框架,支持文件上傳與下載,支持https,由移動支付Square公司貢獻。
依賴
compile 'com.squareup.okhttp3:okhttp:3.8.1'
Get請求
Get方式發送同步請求
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(); } } });
Get方式發送非同步請求
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()); } } });
Post請求
FormBody傳遞鍵值對參數
FormBody body = new FormBody.Builder() //創建信息主體 .add("name", name) .add("sex", department) .add("possword", post) .add("data", formatter.format(getData())) .build();
RequestBody傳遞Json或File對象
//傳遞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傳遞鍵值對對象和 File對象
MultipartBody multipartBody =new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("groupId",""+Id)//添加鍵值對參數 .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件 .build();
Post同步/非同步請求
//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()非同步模式。
同步是在主線程操作,所以需要開啟子線程操作。非同步是CallBack回調回來的Response,是在子線程操作,但是回調的onFailure()和onResponse()依然在子線程中。
respinse.body() 也是在子線程,需要接收到內容,才能調用主線程操作。
註意response.body()只能調用一次,因為是輸出流的讀操作,而讀寫操作只接收一次,第二次會返回null。
設置網路超時
OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS)//設置超時時間 .readTimeout(10, TimeUnit.SECONDS)//設置讀取超時時間 .writeTimeout(10, TimeUnit.SECONDS);//設置寫入超時時間