在改造中接收空体回应
我正在使用改造从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();
}
});
}
在响应中,我收到一个空的body.And服务器响应200 OK。
D/OnResponse: {}
但是当我在浏览器中打开URL时,我在屏幕上获取JSONObject。
你应该尝试像这样的阵列GSON转换器将处理它....
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());
}
}
我想你不理解改造filosofy。 了正确的接口应该是:
public interface SlotsAPI {
/*Retrofit get annotation with our URL
And our method that will return a Json Object
*/
@GET(url)
JSONObject getSlots();
}
当你调用getSlots方法,改造将自动进行HTTP请求和返回的JSONObject。 您将需要从主线程中执行此操作。
我认为这个调用不会是异步的。但在我的情况下,我需要异步调用服务器。所以我使用回调方法。谢谢。 – Viking93
确保@Get的URL是相对路径
@Base网址:始终/
@url结束:不要启动/
例如:
String URL = http://api.co/base/ ;
和
@GET("webservice/syncdown")
JSONObject getSlots();
您可能会收到插槽列表。如果您发送的JSON
@GET(url)
retrofit.Call<List<Slot>> getSlots();
您正在使用翻新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的错误还是我做错了什么? – Viking93
这里同样的问题,answer from curiousMind救了我一天。
更多关于同一主题:如果你需要从一对使用得到的值:
String value = response.body().getAsJsonObject().get("pair_name").getAsString();
请检查您的JSONObject。如果你想在json中获得响应,你必须定义一个响应类型JsonObject而不是JSONObject,否则明确指定接口中的pojo类。
他们的拼写是关闭'JsonObject'和'JSONObject'。我们应该注意一个是'com.google.gson.JsonObject',它由'gson'转换器工厂使用,另外一个'org.json.JSONObject',我们必须使用第一个'com.google.gson.JsonObject' 。 – VSB
你可以提供网址吗? –
对不起,我不能。但它是一个普通的http链接。 – Viking93
我建议你使用诸如Fiddler或Charles之类的工具,并通过它们代理这两种流量。然后,您可以比较请求中的差异并获得想法。 也许是因为UserAgent字符串。 –