OkHttp3的使用

不怕跌倒,所以飞翔

参考文献:
SUN's Cabin
刘望舒
瘟疫幽魂
OyangYujun

1.OkHttp3进行GET请求的简单使用:

1.引入关联

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

这里我引入的是最新的你也可以看看最新的是什么版本

2.创建OkHttpClient对象

OkHttpClient httpClient = new OkHttpClient();

3. 创建一个请求

Request request = new Request.Builder()
                .method("GET", null)/*可以通过method设置请求方式,不指定请求方法时默认是GET请求*/
                .url("https://github.com/hongyangAndroid")
                .build();

4.发送一个请求,这里是把请求封装成一个任务,其实这个请求是一个异步请求

Call call = httpClient.newCall(request);

5.开始异步请求

call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                /*step 5:获取响应体*/
                Log.e(TAG, "onResponse: " + response.body());
               }
        });

这里有很多细节的地方需要注意:

  • 这个 response.body().string()只能调用一次,如果调用多次的话会有异常
  • response.body()有很多方法处理数据,可以是流,也可以是字符串等许多类型,根据业务逻辑自行处理
    整体的流程代码如下:
        /*step 1:创建OkHttpClient对象*/
        OkHttpClient httpClient = new OkHttpClient();
        /*step 2:创建一个请求,不指定请求方法时默认是GET请求*/
        Request request = new Request.Builder()
                .method("GET", null)/*可以通过method设置请求方式*/
                .url("https://github.com/hongyangAndroid")
                .build();
        /*step 3:发送一个请求,这里是把请求封装成一个任务,其实这个请求是一个异步请求*/
        Call call = httpClient.newCall(request);
        /*step 4:开始异步请求*/
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                /*step 5:获取响应体*/
                Log.e(TAG, "onResponse: " + response.body());
            }
        });

2.OkHttp3进行POST请求的简单使用:

其实post请求和get请求都是类似的就是多了传入参数的方法,这里就不一步一步写了,直接贴代码了;

 /*step 1: 同样的需要创建一个OkHttpClick对象*/
        OkHttpClient okHttpClient = new OkHttpClient();

        /*step 2: 创建  FormBody.Builder*/
        FormBody formBody = new FormBody.Builder()
                .add("name", "dsd")
                .build();

        /*step 3: 创建请求*/
        Request request = new Request.Builder().url("http://www.baidu.com")
                .post(formBody)
                .build();

        /*step 4:建立联系 创建Call对象*/;
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse: " + response.body().string());
            }
        });

3.OkHttp3进行POST文件上传:

这里的写法都差不多,就直接贴代码了,下面会有注意事项的;

      // step 1: 创建 OkHttpClient 对象
        OkHttpClient okHttpClient = new OkHttpClient();

        //step 2:创建 RequestBody 以及所需的参数
        //2.1 获取文件
        File file = new File(Environment.getExternalStorageDirectory() + "test.txt");
        //2.2 创建 MediaType 设置上传文件类型
        MediaType MEDIATYPE = MediaType.parse("text/plain; charset=utf-8");
        //2.3 获取请求体
        RequestBody requestBody = RequestBody.create(MEDIATYPE, file);

        //step 3:创建请求
        Request request = new Request.Builder().url("http://www.baidu.com")
                .post(requestBody)
                .build();

        //step 4 建立联系
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // TODO: 17-1-4  请求失败
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // TODO: 17-1-4 请求成功
            }
        });
参数 说明
text/html HTML格式
text/plain 纯文本格式
text/xml XML格式
image/gif gif图片格式
image/jpeg jpg图片格式
image/png png图片格式
application/xhtml+xml XHTML格式
application/xml XML数据格式
application/atom+xml Atom XML聚合格式
application/json JSON数据格式
application/pdf pdf格式
application/msword Word文档格式
application/octet-stream 二进制流数据

4.OkHttp3异步上传Multipart文件

这个应用场景要说明一下,一般上传图片到服务器是时候,还要添加一些其他的字段,比如ID什么的,这里就是简单的举例说明一下:

    OkHttpClient mOkHttpClient = new OkHttpClient();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("title", "wangshu")
            .addFormDataPart("image", "wangshu.jpg",
                    RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
            .build();
    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + "...")
            .url("https://api.imgur.com/3/image")
            .post(requestBody)
            .build();
   mOkHttpClient.newCall(request).enqueue(new Callback() {
       @Override
       public void onFailure(Call call, IOException e) {
           // TODO: 17-1-4  请求失败
       }
       @Override
       public void onResponse(Call call, Response response) throws IOException {
           // TODO: 17-1-4 请求成功
       }
   });

4.设置提升

1.设置一些基本的请求参数

 OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)//链接超时
                .writeTimeout(15, TimeUnit.SECONDS)//写入超时
                .readTimeout(20, TimeUnit.SECONDS);//读取超时

OkHttpClient httpClient = builder.build();//构建出OKHttpClient对象

2.添加公共的请求参数

2.1添加到请求链接的尾部
        Request publicRequest = new Request.Builder()
                .url("https://github.com/hongyangAndroid")
                .build();

        HttpUrl httpUrl = publicRequest
                .url()
                .newBuilder()
                .addQueryParameter("version", "1.0")
                .addQueryParameter("code", "android")
                .build();

        Request request = publicRequest.newBuilder()
                .method(publicRequest.method(), publicRequest.body())
                .url(httpUrl)
                .build();

这个request的Url请求地址就是加上了公共请求参数的地址了,其实就是先创建了一个去收集所有的公共参数,然后在重新构建一个request在进行拼接最后出来的就是拼接好的了;

2.2添加在请求form表单里

这种方式一般不会用。。。

        Request publicRequest = new Request.Builder()
                .url("https://github.com/hongyangAndroid")
                .build();

        FormBody formBody = new FormBody.Builder()/*这个就是表单了*/
                .add("version", "1.0")
                .add("code", "android")
                .build();

        /*默认添加表单后不能添加新的form表单,需要先将RequestBody转成String去拼接*/
        String formString = bodyToString(publicRequest.body());
        formString += ((formString.length() > 0) ? "&" : "") + bodyToString(formBody);

        Request request = publicRequest.newBuilder()
                .method(publicRequest.method(), publicRequest.body())
                 //添加到请求里
                 //string转回成RequestBody
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), formString))
                .build();

    /*转换的方法*/
    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null) copy.writeTo(buffer);
            else return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
2.3添加在请求head
        Request request = publicRequest.newBuilder()
                .method(publicRequest.method(), publicRequest.body())
                .addHeader("version", "1.0")
                .addHeader("code", "android")
                .build();

2.4关于拦截器
2.4.1日志拦截器
public class LogInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Log.e("url", String.format("Sending request %s on %s %n %s", request.url(), chain.connection(), request.headers()));
        return chain.proceed(request);
    }
}

这是一个简单的日志拦截器,作用是拦截打印所有日志,添加的话直接addInterceptor(new LogInterceptor())就可以了,这个里面其实可以重新定制请求的所有信息


关于进阶上的内容以后用到了在添加上去。。。


2017年10月04日添加
关于OkHttp3缓存的使用

  • 首先说明一点,对于OkHttp3缓存的策略,基本上都是针对于GET请求的,因为GET请求都是一些持久的请求,不像POST请求用于交互,所以这里添加的都是针对于GET请求的一些操作。

关于缓存的内容有两种方案:

1.一种方案是:

这种方案是把缓存直接存入到指定目录当中,不论

你可能感兴趣的:(OkHttp3的使用)