如何在Retrofit 2中打印漂亮?

时间:2016-01-26 03:34:51

标签: android gson retrofit2

我的改装设置为HttpLoggingInterceptor,如下所示:

Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
                .setPrettyPrinting() // Pretty print
                .create();

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

在我的Gson实例上,我做了setPrettyPrinting,我仍然得到紧凑的JSON输出。 这是我的图书馆。

compile 'com.google.code.gson:gson:2.5'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'

如何使用Retrofit 2实现漂亮的打印效果? 感谢。

编辑:更新了我的图书馆但仍然没有工作

5 个答案:

答案 0 :(得分:2)

创建自己的自定义HttpLogginInterceptor。

public class CustomHttpLogging implements HttpLoggingInterceptor.Logger {
    @Override
    public void log(String message) {
        final String logName = "OkHttp";
        if (!message.startsWith("{")) {
            Log.d(logName, message);
            return;
        }
        try {
            String prettyPrintJson = new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(message));
            Log.d(logName, prettyPrintJson);
        } catch (JsonSyntaxException m) {
            Log.d(logName, message);
        }
    }
}

在您的客户端中,添加:

OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(new CustomHttpLogging())
            .build();

答案 1 :(得分:2)

受到Tanapruk的回答启发,这就是我使用我的版本改装(2.1.0)和okhttp.logging-interceptor(3.8.1)所做的工作。对不起Kotlin和Java的混合。

此版本适用于打印JSON对象和数组。

class ApiLogger : HttpLoggingInterceptor.Logger {
    override fun log(message: String) {
        val logName = "ApiLogger"
        if (message.startsWith("{") || message.startsWith("[")) {
            try {
                val prettyPrintJson = GsonBuilder().setPrettyPrinting()
                    .create().toJson(JsonParser().parse(message))
                Log.d(logName, prettyPrintJson)
            } catch (m: JsonSyntaxException) {
                Log.d(logName, message)
            }
        } else {
            Log.d(logName, message)
            return
        }
    }
}

在客户端:

OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor httpLoggingInterceptor = 
    new HttpLoggingInterceptor(new ApiLogger());
httpLoggingInterceptor.setLevel(Level.BODY);
httpClientBuilder.addInterceptor(httpLoggingInterceptor);

答案 2 :(得分:1)

感谢Tanapruk Tangphianphan的回答。

我改进了它,以支持Java Platform的所有Android

创建PrettyLogger类

class PrettyLogger implements HttpLoggingInterceptor.Logger {
    private Gson mGson = new GsonBuilder().setPrettyPrinting().create();
    private JsonParser mJsonParser = new JsonParser();

    @Override
    public void log(String message) {
        String trimMessage = message.trim();
        if ((trimMessage.startsWith("{") && trimMessage.endsWith("}"))
                || (trimMessage.startsWith("[") && trimMessage.endsWith("]"))) {
            try {
                String prettyJson = mGson.toJson(mJsonParser.parse(message));
                Platform.get().log(INFO, prettyJson, null);
            } catch (Exception e) {
                Platform.get().log(WARN, message, e);
            }
        } else {
            Platform.get().log(INFO, message, null);
        }
    }
}

在Buidler中使用:

OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new PrettyLogger());
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);

答案 3 :(得分:0)

Beta 2并不总是尊重自定义gson设置。尝试升级到Beta 3。

来自beta 3 change log -

  

修复:Gson转换器现在尊重提供的Gson上的设置   实例(例如serializeNulls)。这需要Gson 2.4或更新版本。

您还需要升级到okhttp3 for beta3。

答案 4 :(得分:0)

不使用gson的Kotlin版本:

HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {

    private fun print(m: String) {
        //Crashlytics.log(m)
        Log.i("API", m)
    }

    override fun log(message: String) {
        if (message.length > 500)
            return print("=== more than 500 characters ===")

        if (message.startsWith("{") || message.startsWith("[")) try {
                JSONObject(message).toString(4).also(::print)
            } catch (e: JSONException) { print(message) }
        else print(message)
    }
}).also { it.level = HttpLoggingInterceptor.Level.BODY }