OkHttp使用心得

2018-01-11  本文已影响0人  KMT丶

简介

OkHttp是一款适用于Android和Java应用程序的HTTP&HTTP2客户端。它有如下特性:

引入

以Java为例,通常使用Maven构建方式,在pom文件中加入依赖。

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.1</version>
</dependency>

get请求

  1. 先实例化okhttp,构建一个request,由于get是默认方式,所以设置一个url地址就可以了,也可以通过Request.Builder设置更多的参数。
  2. 然后通过client创建一个call对象并发送请求。
  3. 通过response.body().string()获取返回的字符串。这个body()其实就是ResponseBody对象。
OkHttpClient client = new OkHttpClient();

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

Response response = client.newCall(request).execute();
String responseBody = response.body().string();

post请求

  1. 提交字符串
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
String str = "abcd";
RequestBody body = RequestBody.create(mediaType, str);

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

Response response = client.newCall(request).execute();
String responseBody = response.body().string();
  1. 提交json
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String json = "{'name':'kmt','sex':'man'}";
RequestBody body = RequestBody.create(mediaType, json);

Request request = new Request.Builder()
    .url(url)
    .post(body)
    .build();
    
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
  1. 提交form表单
OkHttpClient client = new OkHttpClient();

RequestBody body = new FormBody.Builder()
    .add("name", "kmt")
    .add("sex", "man")
    .build();
    
Request request = new Request.Builder()
    .url(url)
    .post(body)
    .build();

Response response = client.newCall(request).execute();
String responseBody = response.body().string();
  1. 上传文件
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("image/png");
File file = new File("/file/test.png");
RequestBody body = RequestBody.create(mediaType, file);

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

Response response = client.newCall(request).execute();
String responseBody = response.body().string();
  1. 提交分块请求
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("image/png");
File file = new File("/file/test.png");
RequestBody fileBody = RequestBody.create(mediaType, file);

RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", "test_img", fileBody)
    .addFormDataPart("name", "kmt")
    .build();

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

Response response = client.newCall(request).execute();
String responseBody = response.body().string();

其他

  1. 设置超时时间
OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10,TimeUnit.SECONDS)
    .writeTimeout(10,TimeUnit.SECONDS)
    .build();
  1. 添加请求头
Request request = new Request.Builder()
    .url(url)
    .addHeader("authorization", authorization)
    .addHeader("content-type", "application/x-www-form-urlencoded")
    .addHeader("cache-control", "no-cache")
    .post(body)
    .build();
  1. 异步

client.newCall(request).execute()是同步的,client.newCall(request).enqueue()是异步的。onFailure是请求失败执行的方法,onResponse是请求成功执行的方法。

client.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 {
        String responseBody = response.body().string();
    }
});
上一篇下一篇

猜你喜欢

热点阅读