繁体   English   中英

Android - 如何在Robospice / retrofit中获取JSON格式请求和响应

[英]Android - How to get JSON format request and response in Robospice/retrofit

我是Robospice /改造图书馆的新手。 我从github得到了一些样本。 https://github.com/octo-online/RoboSpice-samples/tree/release/robospice-sample-retrofit

我的理解:

请求是“githubRequest”,响应是“Contributor.List”。 web服务由getSpiceManager()。execute执行。

代码片段:

    @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请求和响应,我该怎么做? 有人帮我这样做吗?

要打印响应对象,首先通过Callback<Object> cb将回调对象类型更改为通用Object类型。 然后在成功回调中,您可以只记录对象以将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));

我认为您可以配置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);
                }
            });

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM