Okhttp3 - RequestBody.create(contentType, content) Deprecated

Matías picture Matías · Jul 18, 2019 · Viewed 34.5k times · Source

I did not find any example of how to replace the deprecation method. The examples on the okhttp3 main page are old. This is one of them:

public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
      Request request = new Request.Builder()
          .url(url)
          .post(body)
          .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

If someone could solve it, I would appreciate your help.

Update: I'm using 'com.squareup.okhttp3:okhttp:4.0.1'

Answer

YuTang picture YuTang · Aug 14, 2019

Java Solution: Use create(String, MediaType) instead of create(MediaType, String) for example

Kotlin Solution: Use the extension function content.toRequestBody(contentType); for the File type file.asRequestBody(contentType)

Note: I'm using kotlin, but my IDE just doesn't automatically import the class or method like import okhttp3.RequestBody.Companion.toRequestBody, so I import it manually...then use it as the example given by Saeed Younus and Pratyesh below

For more: The documentation

(In Android Studio or any Jetbrain's IDE, the solution to the deprecated methods or class can be found by just holding the Ctrl and clicking on the create(...) of RequestBody.create)