クイックスタートガイドOkHttpは、POSTリクエストを送信します

翻訳者注:HTTPS://www.baeldung.com/記事は、興味のある学生がアクセス学習に行くことができ、英語の技術サイトの非常に高品質です。

1はじめに

この記事では紹介しますOkHttpクライアントの基本的な使い方を。

この簡単な技術的な記事では、我々は要求を送信するために別の方法OkHttp 3.xバージョンのポストを強調表示します。

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

POSTリクエスト権限を持つ3

あなたが認証を要求する場合は、リクエストヘッダに資格を追加するCredentials.basicビルダーを使用することができます。

次のコードは、文字列を許可本体と要求文字列を送信する例を示しています。

@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データ伝送モード

リクエストボディJSONを送信するためには、メディアタイプを設定する必要がありますファイルアプリケーション/ 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リクエストを送信するには、我々はする必要がRequestBodyとして建てMultipartBody文書、ユーザー名とPOSTリクエストをパスワードを公開します:

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

POSTリクエストを送信することなく、6デフォルトの文字エンコーディング

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の上で。

公開された379元の記事 ウォンの賞賛862 ビュー132万+

おすすめ

転載: blog.csdn.net/w605283073/article/details/103797118