2014-08-28 43 views
1

我想实现对使用org.apache包中使用的类的早期项目的改造。Android HttpPost.setEntity()相当于改造

早些时候,我有过这样

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 
); 

然而这使我怀疑一个计算器错误,因为

@Body HttpEntity payload 

并不等同于

HttpPost.setEntity(HttpEntity); 

在这种情况下什么是正确的调用。

回答

3

在改造时,@Body可以是任何类,可以在初始化RestAdapterTypedOutput时使用Converter进行序列化。

通常,如果您在处理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); 
    } 
}; 

然后定义你的接口,像这样

@POST ("/x") 
CustomClass custom(
    @Query("ctid") String ctid, 
    @Body TypedOutput payload 
); 

,并执行它,像这样使用​​对象从上面。

api.custom("1", payload); 

但是如前所述,如果你实际使用JSON工作那么这里就是你如何设置代码一个简单的例子。

比方说,你想要的

{ 
    "firstname": "Parth", 
    "lastname": "Srivastav" 
} 

一个JSON身体,你会创造出你可以调用用户让一个Java类说

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")); 
+0

这是正确的,但更好的方法来得到这个JSON输出是为了让一个类有两个字段,让Gson为你序列化它。 – 2014-08-28 15:43:28

+0

@JakeWharton是正确的,我已经更新了我的帖子,对此有点更清楚。 – 2014-08-28 16:07:36

1

在retrofit2这里是解决方案:

JSONObject jsonObject = {you jsonObject} //change the json to requestBody 
    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),(jsonObject).toString()); 

在POST方法,只需要使用@体,这里有一个例子:

Call<Response> getHostList(@Body RequestBody entery);