モケラ

Tech Sheets

mokelab

OkHttpで、Body付きPOSTリクエストを投げる

最終更新日:2022-05-08

POSTを投げる場合は、Request.Builderオブジェクトのpost()を使います。次はtext/plainなbody付きPOSTリクエストを生成する例です。

String url = mUrlText.getText().toString();
String body = mBodyText.getText().toString();

Request request = new Request.Builder()
        .url(url)
        .post(RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), body))
        .build();

RequestBody.create()はString以外にもいろいろ渡せます。

  • public static RequestBody create(MediaType contentType, ByteString content)
  • public static RequestBody create(MediaType contentType, byte[] content)
  • public static RequestBody create(MediaType contentType, byte[] content, int offset, int byteCount)
  • public static RequestBody create(MediaType contentType, File file)

一覧に戻る