115

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'

Matías
  • 1,200
  • 2
  • 7
  • 8
  • It doesn't seem to be deprecated: https://square.github.io/okhttp/3.x/okhttp/okhttp3/RequestBody.html#create-okhttp3.MediaType-java.lang.String- – JB Nizet Jul 18 '19 at 18:21
  • 1
    I'm using 'com.squareup.okhttp3:okhttp:4.2.1', and every suggestion in this SO and others I've searched for the last 2 hours all are depreciated, or cannot be resolved by the IDE. I've tried importing libraries manually and any other suggestion that I can find on SO and in the okHttp documentation, not thing works. I can't believe that something so widely used is sooo hard to use. If there is anyone out there who can help (Jake?) I just need to call api with a blank postBody. In Postman, it is called like "post(null)" Thanks for any suggestions anyone has in advanced. – jonathan3087 Nov 20 '19 at 17:55

9 Answers9

186

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)

YuTang
  • 1,979
  • 1
  • 5
  • 9
  • 4
    need to import manually *okhttp3.RequestBody.Companion.asRequestBody* to use *file.asReqestBody* and *okhttp3.RequestBody.Companion.toRequestBody* to use *content.toRequestBody* – Master Zzzing Feb 14 '20 at 04:40
  • 1
    @YuTang what is content in content.RequestBody? Does this mean I can pass content:// uri? – Sudhir Singh Khanger Apr 14 '20 at 17:51
  • @Sudhir Khanger the content string can be anything you want to post to the back server-side, like JSON. – YuTang Apr 18 '20 at 02:38
  • for such generic deprecation android studio or intellij should just have a button of fix - rather than only suppress... – DragonFire Jun 07 '20 at 04:45
  • Like what DragonFire said, when your IDE is android studio or intellij. just to locate the cursor on the deprecated fuction, and use ```Alt``` + ```Enter```, choose the fix option, I think that's what you want. – YuTang Jun 07 '20 at 06:18
48

In com.squareup.okhttp3:okhttp:4.1.0

MediaType.get("application/json; charset=utf-8") no more available.

instead this we need to use "application/json; charset=utf-8".toMediaTypeOrNull().

For example how we need to create request body now since okhttp:4.1.0

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody

    val jsonObject = JSONObject()
        jsonObject.put("name", "Ancd test")
        jsonObject.put("city", "delhi")
        jsonObject.put("age", "23")
    val body = jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())

To those wondering where the answers are coming from!

All the alternatives/solutions(as described by the answer) are documented in the corresponding deprecated code! Just manoeuvre to it (the deprecated code) using whichever means your IDE supports. For example, to see the alternative/solution to the deprecated code RequestBody.create(...,...) when using AndroidStudio or any Jetbrain's IDE, just long-press Ctrl and hover over the RequestBody.create(...,...) then click on it when it's hovered over successfully

Mitch
  • 1,556
  • 1
  • 17
  • 17
Pratyesh
  • 686
  • 5
  • 9
24

You need to import these files manually may be this is a bug in android studio. It is not suggested but this is work for Okhttp 4.2.2

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody

and use as

val file = File("path")
file.asRequestBody("image/jpeg".toMediaTypeOrNull())
Saeed Younus
  • 279
  • 3
  • 4
  • could you please help me to implement this code in here https://stackoverflow.com/questions/64744692/how-to-upload-image-in-latest-retrofit-version-using-kotlin-with-the-right-reque ? – sarah Nov 09 '20 at 01:40
12

It was deprecated since version 4.0.0 of okhttp3.

The documentation for that version says

@JvmStatic
    @Deprecated(
        message = "Moved to extension function. Put the 'content' argument first to fix Java",
        replaceWith = ReplaceWith(
            expression = "content.toRequestBody(contentType)",
            imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
        ),
        level = DeprecationLevel.WARNING)
    fun create(contentType: MediaType?, content: String) = content.toRequestBody(contentType)

I haven't tried it but I believe that you should be good by doing the following:

package com.example;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Test {

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


  OkHttpClient client = new OkHttpClient();

  public static void main(String[] args) {

  }

  String post(String url, String json) throws IOException {
    //RequestBody body = RequestBody.create(JSON, json);
    RequestBody body = RequestBody.Companion.create(json, JSON);

    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

}

Update: I tried to compile the file shown above using the following dependency version and RequestBody.Companion.create(json, JSON) doesn't seem to be deprecated.

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.0.0</version>
</dependency>
jlmayorga
  • 413
  • 2
  • 11
  • Thanks jlmayorga, but also RequestBody.Companion.create(json, JSON) is deprecated. And "import okhttp3.RequestBody.Companion.toRequestBody" cannot be resolved. – Matías Jul 18 '19 at 21:31
  • Can you please update your question with information about the dependency version that you use? – jlmayorga Jul 18 '19 at 21:45
  • Yes, I have just done it. I'm using 'com.squareup.okhttp3:okhttp:4.0.1' – Matías Jul 18 '19 at 21:49
  • 1
    Don't import the method ``import okhttp3.RequestBody.Companion.toRequestBody`` just import ``RequestBody`` as in the sample that I provided and you should be good. – jlmayorga Jul 18 '19 at 21:58
  • 1
    I could solve it, I was using create(MediaType, String) "deprecated", instead of create(String, MediaType). Thank you jlmayorga. – Matías Jul 18 '19 at 22:08
7

Can u update like that

val apiRequest = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "edit_group")
val tokenRequest = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), token)
val fileReqBody = RequestBody.create(MediaType.parse("image/*"), file)

to

val apiRequest = "edit_group".toRequestBody("text/plain;charset=utf-8".toMediaType())
val tokenRequest = token.toRequestBody("text/plain;charset=utf-8".toMediaType())
val file = File(path)
val fileReqBody = file.asRequestBody("image/*".toMediaType())
Nankai
  • 931
  • 9
  • 21
4

Just change ResponseBody.create(MediaType.parse("text/json"), plainBody.trim()) to ResponseBody.create(plainBody.trim(),MediaType.parse("text/json"))

2

Just had a quick look at the documentation . It reads deprecated, however the alternative is provided in the doc.
json.toRequestBody(contentType) should do the trick for you.
Below is the documentation link:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/RequestBody.kt

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.Companion.create(json, JSON)
      Request request = new Request.Builder()
          .url(url)
          .post(body)
          .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}
Arpan Kanthal
  • 475
  • 2
  • 7
1

ok according to okhttp 4 many thing updated as official docs

RequestBody.create() is upgraded to File.asRequestBody()

Nitish Kumar
  • 111
  • 3
1

You Just Need To Flip Your Args.

@kotlin.jvm.JvmStatic @kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, file: java.io.File): okhttp3.RequestBody { }

    @kotlin.jvm.JvmStatic @kotlin.Deprecated @kotlin.jvm.JvmOverloads public final fun create(contentType: okhttp3.MediaType?, content: kotlin.ByteArray, offset: kotlin.Int , byteCount: kotlin.Int): okhttp3.RequestBody {}

    @kotlin.jvm.JvmStatic @kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, content: kotlin.String): okhttp3.RequestBody {}

    @kotlin.jvm.JvmStatic @kotlin.Deprecated public final fun create(contentType: okhttp3.MediaType?, content: okio.ByteString): okhttp3.RequestBody { }
Kishan Mevada
  • 662
  • 1
  • 6
  • 17