Okhttp3-不推荐使用RequestBody.create(contentType,content) [英] Okhttp3 - RequestBody.create(contentType, content) Deprecated
问题描述
我没有找到任何有关如何替换弃用方法的示例. okhttp3主页上的示例很旧. 这是其中之一:
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.
更新: 我正在使用'com.squareup.okhttp3:okhttp:4.0.1'
Update: I'm using 'com.squareup.okhttp3:okhttp:4.0.1'
推荐答案
Java解决方案:
例如,使用create(String, MediaType)
代替create(MediaType, String)
科特琳解决方案:
使用扩展功能content.toRequestBody(contentType)
;
对于文件类型file.asRequestBody(contentType)
Kotlin Solution:
Use the extension function content.toRequestBody(contentType)
;
for the File type file.asRequestBody(contentType)
注意:
我正在使用kotlin,但我的IDE不会自动导入import okhttp3.RequestBody.Companion.toRequestBody
之类的类或方法,因此我手动将其导入...然后将其用作 Pratyesh
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
更新: 上面提到的自动导入问题可以通过Android Studio智能提示解决:将光标定位在已弃用的函数调用上,然后按 ALT + ENTER ,您将获得提示列表,例如拍摄如下,第一个选择就是我想要的. 结果: 这样,我们无需弄清楚应该使用什么功能来替换已弃用的功能,也不必担心自动导入问题.
Update: The auto-import problem stated above can be solved by the Android Studio smart tip: locating the cursor at the deprecated function invocation, then press ALT+ENTER, you will get list of tip to choose, like the shot below, the first option is what I want. The result: In that way, we don't need to figure out what function we should use to replace the deprecated one and no need to worry about the auto-import issue.
再次说明:并非在所有情况下都使用智能提示,但是它会为您带来很多帮助.
Note again: Using smart tip is not for all situation like this one, but it will help you a lot.
更多信息:文档
(在Android Studio或任何Jetbrain的IDE中,只需按住 Ctrl 并单击RequestBody.create
的create(...)
,即可找到不赞成使用的方法或类的解决方案)
(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
)
这篇关于Okhttp3-不推荐使用RequestBody.create(contentType,content)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!