【问题标题】:http post setEntity using retrofithttp post setEntity 使用改造
【发布时间】:2016-04-28 15:17:03
【问题描述】:

我最近搬到了 Retrofit,我想用 Retrofit 替换这个 httpost 集实体。我该怎么做。

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

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

这就是我想要做的,但它不起作用,

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

【问题讨论】:

    标签: android http post retrofit


    【解决方案1】:

    终于想通了,添加一个自定义的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);
    

    【讨论】:

      【解决方案2】:

      您可以在 API 接口中使用 Retrofit 中的以下代码向 Post 发送请求

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

      【讨论】:

        猜你喜欢
        • 2015-05-14
        • 2014-10-11
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多