2016-01-22 110 views
0

我最近搬到Retrofit,我想用Retrofit替換這個httpost集合實體。我該怎麼做。http post setEntity using retrofit

JSONObject jsonObject = new JSONObject(); 
    jsonObject.put("childId", childId); 

    HttpPost httpPost = new HttpPost(url); 
    StringEntity entity = new StringEntity(jsonObject.toString()); 
    httpPost.setEntity(entity); 

這就是我要怎樣做,但它dosent工作,

Observable<Item> getListOfFeed(@Body StringEntity params); 

回答

0

終於想出了答案,添加自定義TypedJsonString類,

public class TypedJsonString extends TypedString { 
    public TypedJsonString(String body) { 
     super(body); 
    } 

    @Override public String mimeType() { 
     return "application/json"; 
    } 
} 

我的JSON對象轉換爲TypedJsonString,

TypedJsonString typedJsonString = new TypedJsonString(jsonObject.toString()); 

改變了API類,如下所示,

Observable<Item> getListOfFeed(@Body TypedJsonString typedJsonString); 
0

您可以Post使用下面的代碼在Retrofit發送請求你的API接口內

public interface MyAPI{ 
@FormUrlEncoded 
@POST("rest url") 
Call<Item> loadQuestions(@Field("parameter_name")String order); 
} 

不要忘記提及@FormUrlEncoded,要調用此函數,請使用此

Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl("url") 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 
MyAPI api=retrofit.create(MyAPI.class); 
Call<Item> call=api.loadQuestions("pass your data here"); 
call.enqueue(new Callback<Item>() { 
     @Override 
     public void onResponse(Response<Item> response, Retrofit retrofit) { 
      Log.e("response",response.message()); 

     } 

     @Override 
     public void onFailure(Throwable t) { 

     } 
});