Java Okhttp3 - RequestBody.create(contentType, content) 已弃用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57100451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:18:18  来源:igfitidea点击:

Okhttp3 - RequestBody.create(contentType, content) Deprecated

javaokhttpokhttp3

提问by Matías

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:

我没有找到任何关于如何替换弃用方法的示例。okhttp3 主页上的例子是旧的。这是其中之一:

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'

更新:我正在使用 'com.squareup.okhttp3:okhttp:4.0.1'

回答by Arpan Kanthal

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

刚刚快速浏览了文档。它已被弃用,但文档中提供了替代方案。
json.toRequestBody(contentType) 应该为您解决问题。
以下是文档链接: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();
  }
}

回答by jlmayorga

It was deprecated since version 4.0.0 of okhttp3.

okhttp3 的 4.0.0 版起已弃用。

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.

更新:我尝试使用以下依赖项版本编译上面显示的文件,RequestBody.Companion.create(json, JSON)但似乎没有被弃用。

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.0.0</version>
</dependency>

回答by Pratyesh

In com.squareup.okhttp3:okhttp:4.1.0

在 com.squareup.okhttp3:okhttp:4.1.0

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

MediaType.get("application/json; charset=utf-8")不再可用。

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

相反,我们需要使用"application/json; charset=utf-8".toMediaTypeOrNull().

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

例如,我们现在需要如何创建请求正文,因为 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 AndroidStudioor any Jetbrain's IDE, just long-press Ctrland hover over the RequestBody.create(...,...)then click on it when it's hovered over successfully

所有替代方案/解决方案(如答案所述)都记录在相应的弃用代码中!只需使用您的 IDE 支持的任何一种方式来处理它(已弃用的代码)。例如,要RequestBody.create(...,...)在使用AndroidStudio或任何Jetbrain 的 IDE时查看已弃用代码的替代方案/解决方案,只需长按Ctrl并悬停在 上,RequestBody.create(...,...)然后在悬停成功时单击它

回答by YuTang

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

Java 解决方案:使用create(String, MediaType)代替create(MediaType, String)例如

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

Kotlin 解决方案:使用扩展函数content.toRequestBody(contentType);对于文件类型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 Younusand Pratyeshbelow

注意:我使用的是 kotlin,但我的 IDE 不会自动导入类或方法import okhttp3.RequestBody.Companion.toRequestBody,所以我手动导入...然后将其用作下面Saeed YounusPratyesh给出的示例

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 Ctrland clicking on the create(...)of RequestBody.create)

(在Android Studio中或任何Jetbrain的IDE,解决过时方法或类可以通过只抱着找到Ctrl键并单击create(...)RequestBody.create

回答by Saeed Younus

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

您需要手动导入这些文件,这可能是 android studio 中的一个错误。不建议这样做,但这适用于 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())