防止改造编码我的http请求正文 [英] Prevent retrofit from encoding my http request body

查看:112
本文介绍了防止改造编码我的http请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

param1=PARAM1&param2=PARAM2&param3=PARAM3

但是改装对我的身体进行编码,以便=成为\ u003d和&成为\ 0000。我最终得到一个字符串实际上是这样的:

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

param1\u003dPARAM1\u0026param2\u003dPARAM2\u0026param3\u003dPARAM3

如何防止这种情况?

我的改造休息api定义如下。

My retrofit rest api is defined as follows.

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


推荐答案

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

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

但是,这种有效载荷格式称为表格URL编码。 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:

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

这篇关于防止改造编码我的http请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆