OkHttp使用介紹

準(zhǔn)備

在gradle中添加

compile 'com.squareup.okhttp3:okhttp:3.8.1'

在manifest中添加訪問網(wǎng)絡(luò)權(quán)限

<uses-permission android:name="android.permission.INTERNET"/>

Okhttp網(wǎng)絡(luò)請求分兩種模式 1. 同步請求 (直接在所在請求的線程中進(jìn)行請求操作)2.異步請求(開啟新線程,在OKHttp請求線程池中進(jìn)行請求操作),由于Android 4.0以后不能在主線程中進(jìn)行網(wǎng)絡(luò)請求,會報(bào)android.os.NetworkOnMainThreadException,所以在Android平臺上使用異步請求比較好,在Android使用同步請求的話還是要開子線程。

Get請求

  1. 同步get請求

    private  OkHttpClient mClient=new OkHttpClient();
    public static final String BASE_URL="http://greatfeng.top/app";
    

           new Thread(()-> {
               try {
                   run();
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }).start();

    public void run() throws Exception {
        Request request = new Request.Builder()
                .url(BASE_URL+"/weather?cityname="+"上海")
                .build();

        Response response = mClient.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0; i < responseHeaders.size(); i++) {
            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }

        System.out.println(response.body().string());
    }
    
  1. 異步Get請求
   private  OkHttpClient mClient=new OkHttpClient();

    public static final String BASE_URL="http://greatfeng.top/app";

    public void run() throws Exception {
        Request request = new Request.Builder()
                .url(BASE_URL+"/weather?cityname="+"上海")
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(response.body().string());
            }
        });
    }

post請求

  1. post表單
   private  OkHttpClient mClient=new OkHttpClient();

    public static final String BASE_URL="http://greatfeng.top/app";

    public void run() throws Exception {
        RequestBody formBody = new FormBody.Builder()
                .add("name", "libai")
                .add("pwd", "libai")
                .add("email", "libai@gmail.com")
                .build();
        Request request = new Request.Builder()
                .url(BASE_URL+"/user/signIn")
                .post(formBody)
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(response.body().string());
            }
        });
        
    }
  1. 上傳文件

    private  OkHttpClient mClient=new OkHttpClient();

    public static final String BASE_URL="http://greatfeng.top/app";

    public static final MediaType MEDIA_TYPE_PNG
            = MediaType.parse("image/png");

 public void run() throws Exception {

        File file = new File(Environment.getExternalStorageDirectory(),"DCIM/Camera/9075ed53cf61f8f54bde0d664fd28a80.jpg");

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "ic.jpg",
                        RequestBody.create(MEDIA_TYPE_PNG, file))
                .build();
        Request request = new Request.Builder()
                .url(BASE_URL+"/user/upload")
                .post(requestBody)
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(response.body().string());
            }
        });
    }
  1. 上傳文件加表單
     // 要上傳文件的時候添加表單只需在請求體中加入 .addFormDataPart()添加,其余和之前上傳文件一樣,
    // 請求網(wǎng)址改為.url(BASE_URL+"/user/upload/data")
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("data","hello World")
                .addFormDataPart("file", "ic.jpg",
                        RequestBody.create(MEDIA_TYPE_PNG, file))
                .build();

下載文件



    private static final String TAG = "MainActivity";

    private  OkHttpClient mClient=new OkHttpClient();

    public static final String BASE_URL="http://greatfeng.top/wifi.apk";


   public void run() throws Exception {
        Request request = new Request.Builder()
                .url(BASE_URL)
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {
                    Log.d(TAG, "server contacted and has file");

                    boolean writtenToDisk = writeResponseBodyToDisk(response.body());

                    Log.d(TAG, "file download was a success? " + writtenToDisk);
                } else {
                    Log.d(TAG, "server contact failed");
                }

            }
        });
    }


    private boolean writeResponseBodyToDisk(ResponseBody body) {
        try {

            File file = new File(Environment.getExternalStorageDirectory(),"test.zip");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                    Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                Log.e(TAG, "writeResponseBodyToDisk: ", e);
                return false;
            } finally {

                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "writeResponseBodyToDisk: ",e );
            return false;
        }
    }

添加請求頭

  1. 所有請求都添加請求頭
 Interceptor mInterceptor=new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(chain.request().newBuilder()
                .addHeader("Content-Type", "application/json")
                .build());
    }
    
    
    OkHttpClient mClient = new OkHttpClient.Builder()
                .addInterceptor(mInterceptor)
                .build();
  1. 單個請求添加請求頭
   Request request = new Request.Builder()
                .url("http://incivility.net/download/test.zip")
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .addHeader("Accept", "application/vnd.github.v3+json")
                .build();

取消請求

Call call = mClient.newCall(request);
call.cancel();

配置Timeout

OkHttpClient mClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();

配置單獨(dú)的OkHttpClient

  OkHttpClient copy = mClient.newBuilder()
          .readTimeout(500, TimeUnit.MILLISECONDS)
          .build();

配置basic認(rèn)證

 public void run() throws Exception {

        mClient = new OkHttpClient.Builder()
                .authenticator((Route route, Response response) -> {
                    System.out.println("Authenticating for response: " + response);
                    System.out.println("Challenges: " + response.challenges());

                    String credential = Credentials.basic("tomcat", "tomcats");

                    if (credential.equals(response.request().header("Authorization"))) {
                        return null; // If we already failed with these credentials, don't retry.
                    }
                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                })
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL + "/manager/html")
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(response.body().string());
            }
        });
    }

配置代理

    private OkHttpClient mClient = new OkHttpClient.Builder()
                                    .proxy(new Proxy(
                                    Proxy.Type.HTTP, //代理類型
                                    new InetSocketAddress("代理服務(wù)器地址",代理端口號)))
                                    .proxyAuthenticator(( route,  response)->
                                    {
                                        Request request = response.request();
                                        String credential = Credentials.basic("代理賬號", "代理密碼");
                                        return request.newBuilder()
                                                .header( "Proxy-Authorization" , credential)
                                                .build();
                                    })
                                    .build();

添加打印信息

在gradle中添加

    compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'

   private OkHttpClient mClient = new OkHttpClient.Builder()
                                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                                    .build();

使用cache

Cache-Control
    File cacheFile = new File(App.getAppContext().getCacheDir(), "cache");
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
    OkHttpClient mClient = new OkHttpClient.Builder()
            .addInterceptor(new HttpCacheInterceptor())
            .cache(cache)
            .build();


    class HttpCacheInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!isNetConnected(App.getAppContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                Log.d("Okhttp", "no network");
            }

            Response originalResponse = chain.proceed(request);
            if (isNetConnected(App.getAppContext())) {
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheControl)
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .build();
            }
        }
    }
    public static boolean isNetConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo[] infos = cm.getAllNetworkInfo();
            if (infos != null) {
                for (NetworkInfo ni : infos) {
                    if (ni.isConnected()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,922評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,537評論 19 139
  • OkHttp使用介紹 版權(quán)聲明:歡迎轉(zhuǎn)載,但請保留文章原始出處作者:GavinCT 出處:http://www.c...
    W_Nicotine閱讀 165評論 0 0
  • 1.Nevertheless, the EU representative’s speech was at lea...
    燰未燰來閱讀 275評論 0 0
  • 早上起來讀了郭廣昌寫個復(fù)星同學(xué)們的一封信,核心意思是復(fù)星三駕馬車中的梁信軍(下圖右三)同學(xué)要休息一段時間,在信中郭...
    沈磊閱讀 234評論 0 0

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