我是Robospice / retrofit图书馆的新手。我从github得到了一些样本。 https://github.com/octo-online/RoboSpice-samples/tree/release/robospice-sample-retrofit
我的理解:
请求是“githubRequest”,响应是“Contributor.List”。 web服务由getSpiceManager()。执行。
调用代码段:
@Override
protected void onStart() {
super.onStart();
getSpiceManager().execute(githubRequest, "github", DurationInMillis.ONE_MINUTE, new ListContributorRequestListener());
}
public final class ListContributorRequestListener implements RequestListener<Contributor.List> {
@Override
public void onRequestFailure(SpiceException spiceException) {
Toast.makeText(SampleSpiceActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestSuccess(final Contributor.List result) {
Toast.makeText(SampleSpiceActivity.this, "success", Toast.LENGTH_SHORT).show();
updateContributors(result);
}
}
我的问题:我想从应用程序中检查请求/响应(“githubRequest”/“Contributor.List”)是否将正确的JSON发送到服务。那么如何sysout JSON请求和响应。但请求/响应是POJO对象。但是如果我想打印JSON请求和响应,我该怎么做? 有人帮我这么做吗?
答案 0 :(得分:11)
要打印响应对象,首先通过Object
将回调对象类型更改为通用Callback<Object> cb
类型。然后在成功回调中,您只需记录对象即可将Json格式化版本打印到控制台。
@Override
public void success(Object o, Response response) {
Log.i("Tag", "Login data " + o.toString());
}
要打印请求对象,您可以使用您使用的任何Json库(这里我使用Gson)将请求对象序列化为Json并将其记录到控制台。
Log.i("Tag", "Login data " + new Gson().toJson(requestObject));
答案 1 :(得分:0)
我认为您可以配置Retrofit以便在Log中查看JSON请求和响应。
public class RetrofitSpiceService extends RetrofitGsonSpiceService {
private static final String BASE_URL = "http://your_url_here";
@Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(SomeService.class);
}
@Override
protected String getServerUrl() {
return BASE_URL;
}
@Override
protected Builder createRestAdapterBuilder() {
Gson gson = new GsonBuilder()
.create();
return super.createRestAdapterBuilder()
.setLogLevel(RestAdapter.LogLevel.FULL)
// or .setLog(new AndroidLog("Retrofit"))
.setLog(new RestAdapter.Log() {
@Override
public void log(String msg) {
String[] blacklist = {"Access-Control", "Cache-Control", "Connection", "Content-Type", "Keep-Alive", "Pragma", "Server", "Vary", "X-Powered-By",
"Content-Length", "Set-Cookie", "OkHttp-Selected-Protocol", "OkHttp-Sent-Millis", "OkHttp-Received-Millis"};
for (String bString : blacklist) {
if (msg.startsWith(bString)) {
return;
}
}
Log.d("Retrofit", msg);
}
});
}
}