Quick Start Guide OkHttp send a POST request

Translator's Note: https: //www.baeldung.com/ article is a very high quality of English technology site, interested students can go to access learning.

1 Introduction

This article will introduce OkHttp basic usage of the client.

In this brief technical article, we'll highlight a different way OkHttp 3.x version Post to send the request.

2 substantially POST request

We can use FormBody.Builder basic structure requestBody , it contains two parameters: user name, password, send a POST request.

@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 with a POST request authorization

If you want to request authentication, you can use Credentials.basic builder to add credentials to the request header.

The following code shows an example of transmitting a request string with body authorized 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 JSON data transmission mode

In order to transmit the request body JSON, it must set the media type file application / JSON . We can use RequestBody.create builder to construct:

@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

To send a Multipart Post request, we need to RequestBody built as a MultipartBody to publish documents, user names and passwords POST request:

@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 default character encoding without sending POST request

Okhttp default character encoding is 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 other character encodings, we can use it as MediaType.parse () The second parameter passed:

@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 summary

In this essay, we give a few examples of the use OkHttp POST request sent by the client.

As usual, the sample code in this article has been published in GitHub on.

Published 379 original articles · won praise 862 · Views 1.32 million +

Guess you like

Origin blog.csdn.net/w605283073/article/details/103797118