【发布时间】:2016-05-17 11:18:28
【问题描述】:
Retrofit2 有问题。
当我调用我的网络服务时,即使成功,我的响应正文也是空的。
我尝试使用 RESTClient for Firefox 进行相同的调用,并且正文包含正确答案。
这是我的堆栈跟踪:
D/Call request: Request{method=POST, url=http://myNeo4jServer.com, tag=null}
D/Call request header: Authorization: Basic xxxxxx
Accept: application/json; charset=UTF-8
D/Response raw header: Server: nginx
Date: Tue, 17 May 2016 10:55:13 GMT
Content-Type: application/json
Content-Length: 21549
Connection: keep-alive
Access-Control-Allow-Origin: *
OkHttp-Sent-Millis: 1463482513167
OkHttp-Received-Millis: 1463482513354
D/Response raw: retrofit2.OkHttpCall$NoContentResponseBody@e6c7df
D/Response code: 200
D/Response body: null
如你所见:
Content-Length: 21549(我认为这也包括正文中的字符)
响应码:200
响应正文:空
我做错了什么?
编辑
我的界面:
public interface PhonebookContactAPI {
@Headers({
"Authorization: Basic xxxxxx",
"Accept: application/json; charset=UTF-8",
"Content-Type: application/json"
})
@POST("/db/data/transaction/commit")
Call<ResponseBody> get(@Body RequestBody body);
}
我的要求:
String json = "{\"statements\": [{\"statement\": \"MATCH (n) RETURN n\"}]}";
Retrofit client = new Retrofit.Builder()
.baseUrl(Globals.BASE_CLIENT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
PhonebookContactAPI service = client.create(PhonebookContactAPI.class);
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
Call<ResponseBody> call = service.get(body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Call request", call.request().toString());
Log.d("Call request header", call.request().headers().toString());
Log.d("Response raw header", response.headers().toString());
Log.d("Response raw", String.valueOf(response.raw().body()));
Log.d("Response code", String.valueOf(response.code()));
if(response.isSuccessful()) {
Log.d("Response body", new Gson().toJson(response.body()));
}
else {
Log.d("Response errorBody", String.valueOf(response.errorBody()));
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
【问题讨论】:
-
向我们展示您拨打电话的代码可能会更有帮助。
-
@ishmaelMakitla 感谢您回答我。我刚刚更新了问题:)
-
你能不能把
Log.d("Response body", new Gson().toJson(response.body()));改成Log.d("Response body", response.body().toString());之类的东西,让我们看看你得到的body 是否符合你的预期。如果它引发 NullPointerException,那么它可能表示响应确实为 null。 -
D/响应正文:okhttp3.ResponseBody$1@cda3c8a
-
@LucasPuerari 你能告诉我你是如何解决这个问题的