簡體   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