A Quick Guide to Post Requests with OkHttp – 用OkHttp发布请求的快速指南

最后修改: 2019年 12月 18日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

We cover the basics of the OkHttp client in our Guide to OkHttp.

我们在OkHttp客户端的Guide to OkHttp中介绍了该客户端的基本知识。

In this short tutorial, we’ll look specifically at different types of POST requests for version 3.x of the client.

在这个简短的教程中,我们将具体看一下3.x版客户端的不同类型的POST请求。

2. Basic POST

2.基本的POST

We can use FormBody.Builder to build a basic  RequestBody to send two parameters – username and password – with a POST request:

我们可以使用FormBody.Builder来构建一个基本的RequestBody,以发送两个参数–用户名密码–与一个POST请求。

@Test
public void whenSendPostRequest_thenCorrect() 
  throws IOException {
    RequestBody formBody = new FormBody.Builder()
      .add("username", "test")
      .add("password", "test")
      .build();

    Request request = new Request.Builder()
      .url(BASE_URL + "/users")
      .post(formBody)
      .build();

    Call call = client.newCall(request);
    Response response = call.execute();
    
    assertThat(response.code(), equalTo(200));
}

3. POST with Authorization

3.带有授权的POST

If we want to authenticate the request, we can use the Credentials.basic builder to add credentials to the header.

如果我们想对请求进行认证,我们可以使用Credentials.basic构建器,将证书添加到头文件中。

In this simple example, we’ll also send a String as the body of the request:

在这个简单的例子中,我们也将发送一个String作为请求的主体。

@Test
public void whenSendPostRequestWithAuthorization_thenCorrect() 
  throws IOException {
    String postBody = "test post";
    
    Request request = new Request.Builder()
      .url(URL_SECURED_BY_BASIC_AUTHENTICATION)
      .addHeader("Authorization", Credentials.basic("username", "password"))
      .post(RequestBody.create(
        MediaType.parse("text/x-markdown), postBody))
      .build();

    Call call = client.newCall(request);
    Response response = call.execute();

    assertThat(response.code(), equalTo(200));
}

4. POST with JSON

4.使用JSON的POST

In order to send JSON in the request body, we have to set its media type application/json. We can do that using the RequestBody.create builder:

为了在请求体中发送JSON,我们必须设置其媒体类型application/json。我们可以使用RequestBody.create构建器来完成。

@Test
public void whenPostJson_thenCorrect() throws IOException {
    String json = "{\"id\":1,\"name\":\"John\"}";

    RequestBody body = RequestBody.create(
      MediaType.parse("application/json"), json);

    Request request = new Request.Builder()
      .url(BASE_URL + "/users/detail")
      .post(body)
      .build();
 
    Call call = client.newCall(request);
    Response response = call.execute();

    assertThat(response.code(), equalTo(200));
}

5. Multipart POST Request

5.多部分POST请求

The last example we’ll look at is a POST multipart request. We need to build our RequestBody as a MultipartBody to post a file, a username, and a password:

我们要看的最后一个例子是一个POST多部分请求。我们需要将我们的RequestBody构建为一个MultipartBody来发布一个文件、一个用户名和一个密码。

@Test
public void whenSendMultipartRequest_thenCorrect() 
  throws IOException {	
    RequestBody requestBody = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart("username", "test")
      .addFormDataPart("password", "test")
      .addFormDataPart("file", "file.txt",
        RequestBody.create(MediaType.parse("application/octet-stream"), 
          new File("src/test/resources/test.txt")))
      .build();

    Request request = new Request.Builder()
      .url(BASE_URL + "/users/multipart")
      .post(requestBody)
      .build();

    Call call = client.newCall(request);
    Response response = call.execute();

    assertThat(response.code(), equalTo(200));
}

6. POST with Non-Default Character Encoding

6.使用非默认字符编码的POST

OkHttp’s default character encoding is UTF-8:

OkHttp的默认字符编码是UTF-8。

@Test
public void whenPostJsonWithoutCharset_thenCharsetIsUtf8() throws IOException {
    final String json = "{\"id\":1,\"name\":\"John\"}";

    final RequestBody body = RequestBody.create(
        MediaType.parse("application/json"), json);

    String charset = body.contentType().charset().displayName();

    assertThat(charset, equalTo("UTF-8"));
}

If we want to use a different character encoding, we can pass it as the second parameter of the MediaType.parse():

如果我们想使用不同的字符编码,我们可以把它作为MediaType.parse()的第二个参数传递。

@Test
public void whenPostJsonWithUtf16Charset_thenCharsetIsUtf16() throws IOException {
    final String json = "{\"id\":1,\"name\":\"John\"}";

    final RequestBody body = RequestBody.create(
        MediaType.parse("application/json; charset=utf-16"), json);

    String charset = body.contentType().charset().displayName();

    assertThat(charset, equalTo("UTF-16"));
}

7. Conclusion

7.结语

In this short article, we saw several examples of POST requests with the OkHttp client.

在这篇短文中,我们看到了几个使用OkHttp客户端的POST请求的例子。

As usual, the code examples are available over on GitHub.

像往常一样,代码示例可在GitHub上获得。