1. 序章

OkHttpクライアントの基本についてはOkHttpガイドで説明しています。

この短いチュートリアルでは、クライアントのバージョン3.xに対するさまざまなタイプのPOSTリクエストを具体的に見ていきます。

2. 基本的なPOST

FormBody.Builder を使用して、基本的な RequestBody を作成し、POSTリクエストでユーザー名パスワードの2つのパラメーターを送信できます。

@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

リクエストを認証する場合は、Credentials.basicビルダーを使用してヘッダーに資格情報を追加できます。

この簡単な例では、リクエストの本文として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. JSONを使用したPOST

リクエスト本文で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. マルチパートPOSTリクエスト

最後に説明する例は、POSTマルチパートリクエストです。 ファイル、ユーザー名、パスワードを投稿するには、RequestBodyMultipartBodyとして作成する必要があります。

@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

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"));
}

別の文字エンコードを使用する場合は、 MediaType.parse()の2番目のパラメーターとして渡すことができます。

@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. 結論

この短い記事では、OkHttpクライアントを使用したPOSTリクエストの例をいくつか見てきました。

いつものように、コード例はGitHubから入手できます。