我正在尝试对使用 org.apache 包中的类的早期项目进行改造。
之前我有这样的代码
url.addParameters(url,param); // add query parameters
HttpPost post = new HttpPost(url);
post.setEntity(payload); //InputStreamEntity payload passed as argument
现在在转换为改造时我声明如下
@POST ("/x")
CustomClass custom(
@Query("ctid") String ctid,
@Body HttpEntity payload
);
然而,这给出了一个 stackoverflow 错误,我怀疑这是因为
@Body HttpEntity payload
不等同于
HttpPost.setEntity(HttpEntity);
在这种情况下,正确的调用是什么。
最佳答案
在 Retrofit 中,@Body
可以是任何可以被初始化 RestAdapter
时使用的 Converter
序列化的类,也可以是 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);
}
};
然后像这样定义你的接口(interface)
@POST ("/x")
CustomClass custom(
@Query("ctid") String ctid,
@Body TypedOutput payload
);
然后使用上面的 payload
对象像这样执行它。
api.custom("1", payload);
但如前所述,如果您实际使用 JSON,那么这里有一个如何设置代码的快速示例。
假设您想要一个 JSON 正文
{
"firstname": "Parth",
"lastname": "Srivastav"
}
您将创建一个 Java 类,您可以将其称为 User let say
public class User {
public String firstname;
public String lastname;
public User(String firstname; String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
}
像这样修改你的界面
@POST ("/x")
CustomClass custom(
@Query("ctid") String ctid,
@Body User payload
);
然后像这样使用它
api.custom("1", new User("Parth", "Srivastav"));
关于rest - Android HttpPost.setEntity() 相当于改造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25546944/