改进安卓头文件用户代理没有显示在日志上

时间:2018-06-06 07:58:53

标签: android android-studio retrofit user-agent

我做一个拦截器并像这样设置标题User-Agent

public class UserAgentInterceptor implements Interceptor {

private final String userAgent;

public UserAgentInterceptor(String userAgent) {
    this.userAgent = userAgent;
}

@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    Request requestWithUserAgent = originalRequest.newBuilder()
            .header("User-Agent", userAgent)
            .build();
    return chain.proceed(requestWithUserAgent);
}

}

我添加了这样的log showen

  private RestAdapter getRestAdapterFromUrl(String url)
{
    OkHttpClient okHttp = new OkHttpClient();
    okHttp.setConnectTimeout(18000, TimeUnit.MILLISECONDS);
    okHttp.setReadTimeout(18000, TimeUnit.MILLISECONDS);

    // On ajoute user agent intercepteur

    okHttp.networkInterceptors().add(new UserAgentInterceptor(VersionUtil.getUserAgent()));


    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(url)
            .setClient(new RestoflashClientWrapper(new OkClient(okHttp)))
            //.setConverter(new retrofit.converter.JacksonConverter(jsonMapperUnwrapped))
            .setConverter(new JacksonConverter(jsonMapper,jsonMapperUnwrapped))
                    //.setRequestInterceptor(new RestoFlashRequest())
            .setLogLevel(RestAdapter.LogLevel.FULL);

    builder.setRequestInterceptor(interceptor);
    builder.setLogLevel(RestAdapter.LogLevel.HEADERS_AND_ARGS).setLog(new AndroidLog("RETROFIT_LOG"));
    return builder.build();
}

也代替RestAdapter.LogLevel.HEADERS_AND_ARGS。我尝试了RestAdapter.LogLevel.FULL,但在日志上我可以'在android studio的日志中看到User-Agent标题?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我个人也遇到同样的问题。

new OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))

而且我必须添加一个拦截器,以明确记录标题。

@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder();
    /*log debug info*/
    Request request = requestBuilder.build();
    for (int i = 0; i < request.headers().size(); i++) {
        Timber.tag("OkHttp").d(String.format("%s: %s", request.headers().name(i), request.headers().value(i)));
    }
    return chain.proceed(request);
}

我还使用了一个CurlInterceptor,它允许记录“ curl”,如果您想通过“ Postman”之类的工具进行快速测试,这很有用。

CurlInterceptor示例here

希望能满足您的需求!