等效于Android HttpPost.setEntity()

Par*_*tav 2 rest retrofit

我正在尝试对以前使用org.apache包中的类的项目实施改造。

早些时候我有这样的代码

url.addParameters(url,param); // add query parameters
HttpPost post = new HttpPost(url);
post.setEntity(payload); //InputStreamEntity payload passed as argument
Run Code Online (Sandbox Code Playgroud)

现在,当转换为改造我宣布以下

@POST ("/x")
CustomClass custom(

    @Query("ctid") String ctid,
    @Body HttpEntity payload
);
Run Code Online (Sandbox Code Playgroud)

但这给了我怀疑的stackoverflow错误,因为

@Body HttpEntity payload
Run Code Online (Sandbox Code Playgroud)

不等于

HttpPost.setEntity(HttpEntity);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,正确的电话是什么?

Mig*_*gne 5

在Retrofit中,@Body可以是可以Converter在初始化your RestAdapter或时使用的序列化的任何类TypedOutput

通常,如果您要处理JSON,则只需创建POJO类,该类就会由Retrofit自动序列化为JSON。如果您不使用JSON并可能试图像您的情况那样合并2个库之间的间隙,则可以将InputStreamEntity其包装到自己的实现中TypedOutput

这是一个小例子。

// JSON here is merely used for content, as mentioned use serialization if your content is JSON
String body = "{\"firstname\": \"Parth\", \"lastname\": \"Srivastav\"}";
ByteArrayInputStream inputStream = new ByteArrayInputStream(body.getBytes("UTF-8"));

// Here is your HttpEntity, I've simply created it from a String for demo purposes.
HttpEntity httpEntity = new InputStreamEntity(inputStream, inputStream.available(), ContentType.APPLICATION_JSON);

// Create your own implementation of TypedOutput
TypedOutput payload = new TypedOutput() {
    @Override
    public String fileName() {
        return null;
    }

    @Override
    public String mimeType() {
        return httpEntity.getContentType().getValue();
    }

    @Override
    public long length() {
        return httpEntity.getContentLength();
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        httpEntity.writeTo(out);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后像这样定义您的接口

@POST ("/x")
CustomClass custom(
    @Query("ctid") String ctid,
    @Body TypedOutput payload
);
Run Code Online (Sandbox Code Playgroud)

然后像payload上面一样使用对象执行它。

api.custom("1", payload);
Run Code Online (Sandbox Code Playgroud)

但是如前所述,如果您实际上正在使用JSON,那么这里是一个如何设置代码的快速示例。

假设您想要一个JSON主体

{
    "firstname": "Parth",
    "lastname": "Srivastav"
}
Run Code Online (Sandbox Code Playgroud)

您将创建一个Java类,您可以称其为User。

public class User {
    public String firstname;
    public String lastname;

    public User(String firstname; String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样修改您的界面

@POST ("/x")
CustomClass custom(
    @Query("ctid") String ctid,
    @Body User payload
);
Run Code Online (Sandbox Code Playgroud)

像这样使用

api.custom("1", new User("Parth", "Srivastav"));
Run Code Online (Sandbox Code Playgroud)