OkHttp使用介绍

准备

在gradle中添加

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

在manifest中添加访问网络权限

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

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", "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()添加,其余和之前上传文件一样,
    // 请求网址改为.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

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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,014评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,796评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,484评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,830评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,946评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,114评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,182评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,927评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,369评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,678评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,832评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,533评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,166评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,885评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,128评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,659评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,738评论 2 351

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,884评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,639评论 18 139
  • OkHttp使用介绍 版权声明:欢迎转载,但请保留文章原始出处作者:GavinCT 出处:http://www.c...
    W_Nicotine阅读 129评论 0 0
  • 1.Nevertheless, the EU representative’s speech was at lea...
    燰未燰来阅读 224评论 0 0
  • 早上起来读了郭广昌写个复星同学们的一封信,核心意思是复星三驾马车中的梁信军(下图右三)同学要休息一段时间,在信中郭...
    沈磊阅读 173评论 0 0