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

↘锁芯ラ 提交于 2019-12-06 08:17:59

To print the response object first change the callback object type to the generic Object type via Callback<Object> cb. Then in your success callback you can just log the object to print the Json formatted version to the console.

@Override
public void success(Object o, Response response) {
    Log.i("Tag", "Login data " + o.toString());
}

To print the request object you can use whatever Json library you use (here I'm using Gson) to serialize the request object to Json and log that to the console.

Log.i("Tag", "Login data " + new Gson().toJson(requestObject));

I think you can configure Retrofit in order to see JSON request and response in Log.

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);
                }
            });

}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!