java 防止改造编码我的 http 请求正文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26637340/
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-11-02 10:17:56  来源:igfitidea点击:

Prevent retrofit from encoding my http request body

javajsonretrofit

提问by user672009

I'm trying to pass a string of the format below as the body of a http post request.

我正在尝试将以下格式的字符串作为 http 发布请求的正文传递。

param1=PARAM1&param2=PARAM2&param3=PARAM3

But retrofit encodes my body so that = becomes \u003d and & becomes \u0026. And I end up with a string which actually looks like this:

但是改造对我的身体进行编码,以便 = 变为 \u003d 并且 & 变为 \u0026。我最终得到一个实际上看起来像这样的字符串:

param1\u003dPARAM1\u0026param2\u003dPARAM2\u0026param3\u003dPARAM3

How can I prevent that?

我怎样才能防止这种情况?

My retrofit rest api is defined as follows.

我的改造 rest api 定义如下。

public interface RestAPI {
    @POST("/oauth/token")
    public void getAccessToken(@Body String requestBody, Callback<Response> response);
}

采纳答案by Jake Wharton

To answer the question directly, you can use TypedStringas the method parameter type. The reason the value is being changed is because Retrofit is handing the Stringto Gson in order to encode as JSON. Using TypedStringor any TypedOutputsubclass will prevent this behavior, basically telling Retrofit you will handle creating the direct request body yourself.

要直接回答问题,您可以使用TypedString作为方法参数类型。更改值的原因是因为 Retrofit 将 交给StringGson 以编码为 JSON。使用TypedString或 任何子TypedOutput类都会阻止这种行为,基本上告诉 Retrofit 你将自己处理创建直接请求体。

However, that format of payload is called form URL encoding. Retrofit has native support for it. Your method declaration should actually look like this:

但是,这种有效负载格式称为表单 URL 编码。Retrofit 对它有原生支持。您的方法声明实际上应如下所示:

@FormUrlEncoded
@POST("/oauth/token")
void getAccessToken(
    @Field("param1") String param1,
    @Field("param2") String param2,
    @Field("param3") String param3,
    Callback<Response> callback);

回答by Murat ?gat

If you have a serialized class (like a HashMap) in the request body and you want to prevent encoding that (like in vezikon's and my problem), you can create a custom Gson with disabled escaping using:

如果您在请求正文中有一个序列化类(如 HashMap),并且您想阻止对其进行编码(如在 vezikon 和我的问题中),您可以使用以下方法创建一个禁用转义的自定义 Gson:

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

Pass this converter to your rest adapter:

将此转换器传递给您的其余适配器:

yourRestAdapter  = new RestAdapter.Builder()
    .setEndpoint(.....)
    .setClient(.....)
    .setConverter(new GsonConverter(gson))
    .build();

This way the "=" characters in the post body stay intact while submitting.

这样,帖子正文中的“=”字符在提交时保持不变。

回答by hnilsen

Using Kotlin

使用 Kotlin

For Retrofit 2 you can initialize retrofit with a Gson converter factory.

对于 Retrofit 2,您可以使用 Gson 转换器工厂初始化改造。

val builder = GsonBuilder().disableHtmlEscaping().create()
val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(builder))
        .client(monoOkHttpClient())
        .build()

This builder should remove escaping from your json output.

这个构建器应该从你的 json 输出中删除转义。

Gradle file dependencies:

Gradle 文件依赖项:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

回答by Rasool Mohamed

This issue can be fixed with below workaround.

可以使用以下解决方法修复此问题。

@POST("yourString")
Call<YourResponseModel> yourCallMethod(@Query("yourKey") String yourValue,
                                          @Query("yourKey") String yourValue,
                                          @Query("yourKey") String yourValue);

Note : Don't use "@FormUrlEncoded" for this case.

注意:不要在这种情况下使用“@FormUrlEncoded”。

Reference Here - https://github.com/square/retrofit/issues/1407

参考这里 - https://github.com/square/retrofit/issues/1407