OkHttp使用介绍

准备

在gradle中添加

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

在manifest中添加访问网络权限


Okhttp网络请求分两种模式 1. 同步请求 (直接在所在请求的线程中进行请求操作)2.异步请求(开启新线程,在OKHttp请求线程池中进行请求操作),由于Android 4.0以后不能在主线程中进行网络请求,会报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", "[email protected]")
                .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()添加,其余和之前上传文件一样,
    // 请求网址改为.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();

配置单独的OkHttpClient

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

配置basic认证

 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("代理服务器地址",代理端口号)))
                                    .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

OkHttp使用介绍_第1张图片
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;
    }

你可能感兴趣的:(OkHttp使用介绍)