Android OkHttp3的詳細(xì)使用

OkHttp3簡(jiǎn)介

1.支持http和https協(xié)議,api相同,易用;
2.http使用線程池,https使用多路復(fù)用;
3.okhttp支持同步和異步調(diào)用;
4.支持普通form和文件上傳form;
5.操作請(qǐng)求和響應(yīng)(日志,請(qǐng)求頭,body等);
6.okhttp可以設(shè)置緩存;
7.支持透明的gzip壓縮響應(yīng)體

OkHttp3 配置

1.Android Studio 配置gradle:
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
2,添加網(wǎng)絡(luò)權(quán)限:
<uses-permission android:name="android.permission.INTERNET"/>

OkHttp3 使用思路
get請(qǐng)求思路

1.獲取okHttpClient對(duì)象
2.構(gòu)建Request對(duì)象
3.構(gòu)建Call對(duì)象
4.通過(guò)Call.enqueue(callback)方法來(lái)提交異步請(qǐng)求;execute()方法實(shí)現(xiàn)同步請(qǐng)求

post請(qǐng)求思路

1.獲取okHttpClient對(duì)象
2.創(chuàng)建RequestBody
3.構(gòu)建Request對(duì)象
4.構(gòu)建Call對(duì)象
5.通過(guò)Call.enqueue(callback)方法來(lái)提交異步請(qǐng)求;execute()方法實(shí)現(xiàn)同步請(qǐng)求

GET請(qǐng)求

發(fā)送異步請(qǐng)求
    //第一步獲取okHttpClient對(duì)象
    OkHttpClient client = new OkHttpClient.Builder()
            .build();
    //第二步構(gòu)建Request對(duì)象
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    //第三步構(gòu)建Call對(duì)象
    Call call = client.newCall(request);
    //第四步:異步get請(qǐng)求
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("onFailure", e.getMessage());
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = response.body().string();
            Log.i("result", result);
        }
    });
發(fā)送同步請(qǐng)求
    //第一步獲取okHttpClient對(duì)象
    OkHttpClient client = new OkHttpClient.Builder()
            .build();
    //第二步構(gòu)建Request對(duì)象
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
    //第三步構(gòu)建Call對(duì)象
    final Call call = client.newCall(request);
    //第四步:同步get請(qǐng)求
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Response response = call.execute();//必須子線程執(zhí)行
                String result = response.body().string();
                Log.i("response", result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

OkHttp3 發(fā)送異步請(qǐng)求(POST)

    //接口參數(shù) String username,String password

    String url = "http://";
    //第一步創(chuàng)建OKHttpClient
    OkHttpClient client = new OkHttpClient.Builder()
            .build();
    //第二步創(chuàng)建RequestBody(Form表達(dá))
    RequestBody body = new FormBody.Builder()
            .add("username", "admin")
            .add("password", "123456")
            .build();
    //第三步創(chuàng)建Rquest
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    //第四步創(chuàng)建call回調(diào)對(duì)象
    final Call call = client.newCall(request);
    //第五步發(fā)起請(qǐng)求
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("onFailure", e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = response.body().string();
            Log.i("result", result);
        }
    });

OkHttp3 發(fā)送同步請(qǐng)求(POST)

    //接口參數(shù) String username,String password

    String url = "http://";
    //第一步創(chuàng)建OKHttpClient
    OkHttpClient client = new OkHttpClient.Builder()
            .build();
    //第二步創(chuàng)建RequestBody
    RequestBody body = new FormBody.Builder()
            .add("username", "admin")
            .add("password", "123456")
            .build();
    //第三步創(chuàng)建Rquest
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    //第四步創(chuàng)建call回調(diào)對(duì)象
    final Call call = client.newCall(request);
    //第五步發(fā)起請(qǐng)求
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Response response = call.execute();
                String result = response.body().string();
                Log.i("response", result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start(); 

請(qǐng)求頭處理(Header)以及超時(shí)和緩沖處理以及響應(yīng)處理

    //超時(shí)設(shè)置
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5,TimeUnit.SECONDS)
            .readTimeout(5,TimeUnit.SECONDS)
            .writeTimeout(5,TimeUnit.SECONDS)
            .cache(new Cache(cacheDirectory,10*1024*1024))
            .build();

    //表單提交
    RequestBody requestBody = new FormBody.Builder()
            .add("pno", "1")
            .add("ps","50")
            .add("dtype","son")
            .add("key","4a7cf244fd7efbd17ecbf0cb8e4d1c85")
            .build();

    //請(qǐng)求頭設(shè)置
    Request request = new Request.Builder()
            .url(url)
            .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            .header("User-Agent", "OkHttp Example")
            .post(body)
            .build();
  
    //響應(yīng)處理
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //響應(yīng)行
        Log.d("ok", response.protocol() + " " +response.code() + " " + response.message());
        //響應(yīng)頭
        Headers headers = response.headers();
        for (int i = 0; i < headers.size(); i++) {
            Log.d("ok", headers.name(i) + ":" + headers.value(i));
        }
        //響應(yīng)體
        final String string = response.body().string();

        Log.d("ok", "onResponse: " + string);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tx.setText(string);
            }
        });
    }

請(qǐng)求體處理(Form表單,String字符串,流,文件)

    //1.POST方式提交String/JSON    application/json;json串
    MediaType mediaType1 = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
    String requestBody = "pno=1&ps=50&dtype=son&key=4a7cf244fd7efbd17ecbf0cb8e4d1c85";
    RequestBody requestBody1 = RequestBody.create(mediaType1, requestBody);

    //POST方式提交JSON:傳遞JSON同時(shí)設(shè)置son類型頭
    RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), "{}");
    request.addHeader("Content-Type", "application/json")//必須加json類型頭
        
    //POST方式提交無(wú)參
    RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), "");


    //2.POST方式提交流
    RequestBody requestBody2 = new RequestBody() {
        @Nullable
        @Override
        public MediaType contentType() {
            return MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("pno=1&ps=50&dtype=son&key=4a7cf244fd7efbd17ecbf0cb8e4d1c85");
        }
    };

   //3.POST方式提交表單
    RequestBody requestBody4 = new FormBody.Builder()
            .add("pno", "1")
            .add("ps","50")
            .add("dtype","son")
            .add("key","4a7cf244fd7efbd17ecbf0cb8e4d1c85")
            .build();

    //4.POST提交文件
    MediaType mediaType3 = MediaType.parse("text/x-markdown; charset=utf-8");
    File file = new File("test.txt");
    RequestBody requestBody3 = RequestBody.create(mediaType3, file);

    //5.POST方式提交分塊請(qǐng)求
    MultipartBody body = new MultipartBody.Builder("AaB03x")
            .setType(MultipartBody.FORM)
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
                    RequestBody.create(null, "Square Logo"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"image\""),
                    RequestBody.create(MediaType.parse("image/png"), new File("website/static/logo-square.png")))
            .build();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容