喵♂呜 的博客

一个刚毕业就当爹的程序猿 正在迷雾中寻找道路...

OkHttp3 使用和相关问题

本文记录 OkHttp 常用使用方式和常见问题解决

初始化客户端

1
2
3
4
5
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();

超时时间设置

  • 超时时间可以在客户端初始化的时候设置
  • 也可以通过实例重新设置
    1
    2
    3
    client.setConnectTimeout(10, TimeUnit.SECONDS);  
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(20, TimeUnit.SECONDS);

创建表单Body

1
2
3
4
FormBody body = new FormBody.Builder()
.add("name", "android基础")
.add("price", "50")
.build();

创建文件请求

1
2
MediaType type = MediaType.parse("application/octet-stream");
RequestBody fileBody = RequestBody.create(type, Paths.get(path, image).toFile());

创建JSON请求

1
2
3
4
5
Map<String,String> map = new HashMap<>();
map.put("name", "MiaoWoo");
map.put("age", "23");
MediaType type = MediaType.parse("application/json; charset=UTF-8");
RequestBody body = RequestBody.create(type, JSON.toJSONString(map));

创建复合请求

1
2
3
4
5
6
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.ALTERNATIVE)
.addFormDataPart("name", "MiaoWoo")
.addFormDataPart("age", "23")
.addFormDataPart("file", image, fileBody)
.build();

POST请求

  • 创建请求

    1
    2
    3
    4
    5
    6
    7
    // 创建 Request
    Request request = new Request.Builder()
    // 请求的地址
    .url("http://127.0.0.1:8080/api")
    // 上面创建的body
    .post(body)
    .build();
  • 同步处理

    1
    Response response = client.newCall(request).execute()
  • 异步处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    Call call = client.newCall(request);
    Callback callback = new Callback() {//4.回调方法
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    String result = response.body().string();//5.获得网络数据
    }
    }
    call.enqueue(callback);

添加日志调试功能

  • pom文件添加相关依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>logging-interceptor</artifactId>
    <version>3.5.0</version>
    </dependency>
  • 初始化请求客户端

    1
    2
    3
    HttpLoggingInterceptor hli = new HttpLoggingInterceptor(Log::info);
    hli.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient CLIENT = new OkHttpClient.Builder().addNetworkInterceptor(hli).build();
  • 设置应用程序日志等级

    • 设置application.yml
    1
    2
    logging.level:
    <FeignClient全路径类名>: DEBUG
  • 日志效果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    00:30  INFO: --> POST http://jst.dashengcloud.com/openapi/param2/1/com.alibaba.product/alibaba.product.get/4784738 http/1.1
    00:30 INFO: Content-Type: application/x-www-form-urlencoded
    00:30 INFO: Content-Length: 168
    00:30 INFO: Host: jst.dashengcloud.com
    00:30 INFO: Connection: Keep-Alive
    00:30 INFO: Accept-Encoding: gzip
    00:30 INFO: User-Agent: okhttp/3.8.1
    00:30 INFO:
    00:30 INFO: webSite=1688&access_token=0690baf7-f8e8-499c-85a9-c2829be50c4f&productID=1224556382&_aop_timestamp=1521118590479&_aop_signature=9B6A63E56C5B7600F340A3C104F70A0EFF015D06
    00:30 INFO: --> END POST (168-byte body)
    00:30 INFO: <-- 400 Bad Request http://jst.dashengcloud.com/openapi/param2/1/com.alibaba.product/alibaba.product.get/4784738 (44ms)
    00:30 INFO: Server: nginx
    00:30 INFO: Date: Thu, 15 Mar 2018 13:00:04 GMT
    00:30 INFO: Content-Type: application/json; charset=UTF-8
    00:30 INFO: Content-Length: 147
    00:30 INFO: Connection: keep-alive
    00:30 INFO: Access-Control-Allow-Origin: *
    00:30 INFO: Access-Control-Allow-Methods: POST, GET, OPTIONS
    00:30 INFO: Access-Control-Allow-Headers: X-Requested-With,X-Sequence,_aop_secret,_aop_signature,X-Sign-HMAC,Content-Type
    00:30 INFO: Access-Control-Max-Age: 172800
    00:30 INFO: RequestId: 0ab06b5djejean68-15756377
    00:30 INFO:
    00:30 INFO: {"request_id":"0ab06b5djejean68-15756377","exception":"Timestamp expired.","error_message":"Timestamp expired.","error_code":"gw.TimestampExpired"}
    00:30 INFO: <-- END HTTP (147-byte body)

欢迎关注我的其它发布渠道