【问题标题】:Receiving an empty body in retrofit Response在改造响应中接收空体
【发布时间】:2016-06-30 01:12:29
【问题描述】:

我正在使用改造从 http URL 获取数据。 我的接口类:

public interface SlotsAPI {

    /*Retrofit get annotation with our URL
      And our method that will return a Json Object
    */
    @GET(url)
    retrofit.Call<JSONObject> getSlots();
}

我的请求方法。

public void getResponse(){

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

    //Creating an object of our api interface
    SlotsAPI api = retrofit.create(SlotsAPI.class);
    retrofit.Call<JSONObject> callback = api.getSlots();
    callback.enqueue(new Callback<JSONObject>() {
    @Override
    public void onResponse(Response<JSONObject> response) {
        if (response != null) {
            Log.d("OnResponse", response.body().toString());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
    });
}

在响应中,我收到一个空的正文。服务器以 200 OK 响应。

D/OnResponse: {}

但是当我在浏览器中打开 URL 时,屏幕上出现了 JSONObject。

【问题讨论】:

  • 你能提供网址吗?
  • 对不起,我不能。但这是一个常规的 http 链接。
  • 我建议您使用诸如 Fiddler 或 Charles 之类的工具,并通过它们代理两个流量。然后,您可以比较请求中的差异并获得一个想法。也许是因为 UserAgent 字符串。

标签: android json gson retrofit2


【解决方案1】:

你应该这样尝试......

public interface SlotsAPI {

/*Retrofit get annotation with our URL
  And our method that will return a Json Object
*/
@GET(url)
Call<JsonElement> getSlots();
}

在请求方法中

 retrofit.Call<JsonElement> callback = api.getSlots();
callback.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Response<JsonElement> response) {
    if (response != null) {
        Log.d("OnResponse", response.body().toString());
    }
}

【讨论】:

  • 非常感谢@curiousMind。我被困在这里很久了。
  • @user1035292 编码愉快 :)
【解决方案2】:

请检查您的 JsonObject。如果你想在 json 中得到响应,你必须定义一个响应类型 JsonObject 而不是 JSONObject 否则在你的界面中指定 pojo 类。

【讨论】:

  • 它们的拼写接近 JsonObjectJSONObject。我们应该注意,一个是com.google.gson.JsonObject,由gson转换器工厂使用,另一个是`org.json.JSONObject`,我们必须使用第一个,即com.google.gson.JsonObject
【解决方案3】:

我认为您不了解改造 filosofy。 正确的界面应该是:

public interface SlotsAPI {

    /*Retrofit get annotation with our URL
      And our method that will return a Json Object
    */
    @GET(url)
    JSONObject getSlots();
}

当您调用 getSlots 方法时,retrofit 会自动执行 HTTP 请求并返回 JSONObject。 您需要在主线程之外执行此操作。

【讨论】:

  • 我认为调用不会是异步的。但在我的情况下,我需要异步调用服务器。所以我使用回调方法。谢谢。
【解决方案4】:

确保@Get的url是相对路径

  • @Base URL:总是以 / 结尾

  • @Url:不要以 /

  • 开头

例子:

  String URL = http://api.co/base/ ;

  @GET("webservice/syncdown")
  JSONObject getSlots();

您可能会收到一个插槽列表。如果您发送 json 数组,Gson 转换器将处理它

 @GET(url)
 retrofit.Call<List<Slot>> getSlots();

【讨论】:

  • 我会试试这个,让你知道这是否有效。谢谢。
  • 不,它仍然给出相同的空体。
  • 我有一个问题,您确定从您检索的对象的类型中您正在设置转换器工厂 GsonConverterFactory 并且响应正文也是 JSONObject 吗?查看我的更新以了解我的问题
【解决方案5】:

您使用的是改造 2 还是改造 1?版本 2 仍处于测试阶段。 如果您使用的是版本 1。使用此:

public interface SlotsAPI {

    /*Retrofit get annotation with our URL
      And our method that will return a Json Object
    */
    @GET(url)
    void getSlots(Callback<JsonElement> callback);
}

这样调用将是异步的。

【讨论】:

  • 我正在使用 Retrofit 2。我知道 2 处于测试阶段。那么你确定是 2.0 有问题还是我做错了什么?
【解决方案6】:

同样的问题,answer from curiousMind 拯救了我的一天。
关于同一主题的更多信息:如果您需要从一对中获取值,请使用:

String value = response.body().getAsJsonObject().get("pair_name").getAsString();

【讨论】:

    【解决方案7】:

    Call getSlots() 为我工作。

    【讨论】:

      【解决方案8】:
       private void APIRetrofit_method() {
            Retrofit  retrofit = new Retrofit.Builder()
                      .baseUrl(RecyclerInterface.JSONURL)
                     // .client(okHttpClient)
                      .addConverterFactory(GsonConverterFactory.create())
                      .build();
              RecyclerInterface api = retrofit.create(RecyclerInterface.class);
      
              Call<ResponseBody> call = api.getString(); /// GET METHOD without passing params
              // Post METHOD CODE START
      //        HashMap<String, String> params = new HashMap<String, String>();
      //        params.put("name", "yuva");
      //        params.put("pass", "" + "123");
           //   Call<ResponseBody> call1 = api.getProspectList(params);
              // Post METHOD CODE END
      

      【讨论】:

        【解决方案9】:
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                           try {
                                Log.d(TAG, "GetProspectlistresponse" + "" + response.isSuccessful());
                                utility.hideProgressDialog();
                                if (response.isSuccessful()) {
        
                                    String remoteResponse = new String(response.body().string());
                                    Log.d(TAG, "Holidaylistresponse" + "" + remoteResponse);
                                    try {
        
                    JSONObject object = new JSONObject(remoteResponse);
                    JSONArray array = object.getJSONArray("Holidays_Details");
        
                    if (array.toString().equals("[]")) {
                        holiday_recyclerView.setVisibility(View.GONE);
                    } else {
                        holiday_recyclerView.setVisibility(View.VISIBLE);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject c = array.getJSONObject(i);
                            String holidayDate = c.getString(TAG_HOLIDAYDATE);
                            String holidayName = c.getString(TAG_HOLIDAYName);
                            String holidaytype = c.getString(TAG_HOLIDAYtype);
        
                            HashMap<String, String> customers = new HashMap<String, String>();
        
                            customers.put(TAG_HOLIDAYDATE, holidayDate);
                            customers.put(TAG_HOLIDAYName, holidayName);
                            customers.put(TAG_HOLIDAYtype, holidaytype);
                            arrayList.add(customers);
                        }
        
                        getHolidaylistAdapter.notifyDataSetChanged();
                    }
        
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    utility.hideProgressDialog();
            }
                        } catch (IOException e) {
                                    e.printStackTrace();
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("ErrorResponsestring", call.toString());
                    }
                });
            }
        String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
            @GET("json_parsing.php")
            Call<ResponseBody> getString();
        //    @POST("getProspectList")
        //    @FormUrlEncoded
        //    Call<ResponseBody> getProspectList(@FieldMap HashMap<String, String> body);
         implementation 'com.squareup.retrofit2:retrofit:2.0.2'
            implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
            implementation 'com.squareup.okhttp3:okhttp:4.0.0'
        

        【讨论】:

          猜你喜欢
          • 2018-11-04
          • 2016-02-18
          • 2017-01-15
          • 1970-01-01
          • 2018-05-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多