深入解析OkHttp3

原文转载: 深入解析OkHttp3.

1. 特点

OkHttp是一个精巧的网络请求库,有如下特性:

  • 支持http2,对一台机器的所有请求共享同一个socket
  • 内置连接池,支持连接复用,减少延迟
  • 支持透明的gzip压缩响应体
  • 通过缓存避免重复的请求
  • 请求失败时自动重试主机的其他ip,自动重定向
  • 好用的API

2. 基本使用

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

2.1 OkHttp的基本使用,get请求

    String url = "http://www.baidu.com";
    OkHttpClient mHttpClient = new OkHttpClient();

    Request request = new Request.Builder().url(url).build();
    okhttp3.Response response = null;
    try {
      
            response = mHttpClient.newCall(request).execute();
            String json = response.body().string();
            Log.d("okHttp",json);
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}

他说execute()是同步方法
异步使用enqueue()方法,需要回调函数

public void requestBlog() {
     String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
     
     OkHttpClient mHttpClient = new OkHttpClient();
     Request request = new Request.Builder().url(url).build();
     
     mHttpClient.newCall(request).enqueue(new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {

         }

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

2.2 OkHttp的基本使用,post请求

private void post(String url, String json) throws IOException {
     OkHttpClient client = new OkHttpClient();
     
     //还有一种使用json的
     //String json = "haha";
     //RequestBody body = RequestBody.create(JSON, json);
     RequestBody formBody = new FormBody.Builder()
             .add("name", "liming")
             .add("school", "beida")
             .build();

     Request request = new Request.Builder()
             .url(url)
             .post(formBody)
             .build();

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

         }

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

         }

     });
 }

异步上传文件

    OkHttpClient mOkHttpClient = new OkHttpClient();
    File file = new File("/sdcard/demo.txt");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

异步上传字符串

    OkHttpClient client = new OkHttpClient();

    String postBody = ""
            + "Releases\n"
            + "--------\n"
            + "\n"
            + " * zhangfei\n"
            + " * guanyu\n"
            + " * liubei\n";

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .build();

提交分块请求

    OkHttpClient client = new OkHttpClient();

    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    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(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/image")
            .post(body)
            .build();

响应缓存

int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cache(cache);
OkHttpClient client = builder.build();

Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

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

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String response1Body = response.body().string();
        System.out.println("Response 1 response:          " + response);
        System.out.println("Response 1 cache response:    " + response.cacheResponse());
        System.out.println("Response 1 network response:  " + response.networkResponse());
    }

});

超时

private void ConfigureTimeouts() {

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    OkHttpClient client = builder.build();

    client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
    client.newBuilder().readTimeout(10,TimeUnit.SECONDS);
    client.newBuilder().writeTimeout(10,TimeUnit.SECONDS);

    Request request = new Request.Builder()
            .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
            .build();

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

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            System.out.println("Response completed: " + response);
        }
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值