我无法在Retrofit API中找到用于记录完整请求/响应主体的相关方法。一世 期待在Profiler中提供一些帮助(但它只提供有关响应的元数据)。我尝试在Builder中设置日志级别,但这对我没有帮助:
RestAdapter adapter = (new RestAdapter.Builder()).
setEndpoint(baseUrl).
setRequestInterceptor(interceptor).
setProfiler(profiler).
setClient(client).
setExecutors(MyApplication.getWebServiceThreadPool()).
setLogLevel(LogLevel.FULL).
setLog(new RestAdapter.Log() {
@Override
public void log(String msg) {
Log.i(TAG, msg);
}
}).
build();
编辑:此代码现在正在运行。我不知道它为什么不提前工作。可能是因为我正在使用一些旧版本的改造。
答案 0 :(得分:100)
改造2.0 :
更新:@byMarcusPöhls
登录Retrofit 2
Retrofit 2完全依赖OkHttp进行任何网络操作。由于OkHttp是Retrofit 2的对等依赖项,因此一旦Retrofit 2作为稳定版本发布,您就不需要添加额外的依赖项。
OkHttp 2.6.0附带一个日志拦截器作为内部依赖项,您可以直接将它用于您的Retrofit客户端。 Retrofit 2.0.0-beta2仍然使用OkHttp 2.5.0。未来的版本将对更高的OkHttp版本产生依赖性。这就是您需要手动导入日志记录拦截器的原因。将以下行添加到build.gradle文件中的gradle导入中,以获取日志记录拦截器依赖项。
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
You can also visit Square's GitHub page about this interceptor
将记录添加到改造2
在开发应用程序并进行调试时,最好集成一个日志功能来显示请求和响应信息。由于在Retrofit 2中不再默认集成日志记录,因此我们需要为OkHttp添加日志记录拦截器。幸运的是OkHttp已经附带了这个拦截器,你只需要为你的OkHttpClient激活它。
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
我们建议将日志记录添加为最后一个拦截器,因为这也会将您在先前拦截器中添加的信息记录到您的请求中。
日志级别
记录太多信息会炸毁您的Android显示器,这就是为什么OkHttp的日志拦截器有四个日志级别:NONE,BASIC,HEADERS,BODY。我们将引导您完成每个日志级别并描述其输出。
更多信息,请访问:Retrofit 2 — Log Requests and Responses
OLD ANSWER:
不再登录Retrofit 2。开发团队删除了日志记录功能。说实话,记录功能无论如何都不可靠。杰克沃顿明确表示,记录的消息或对象是假定值,并且无法证明它们是真实的。到达服务器的实际请求可能具有已更改的请求正文或其他内容。
即使默认情况下没有集成日志记录,您也可以利用任何Java记录器并在定制的OkHttp拦截器中使用它。
有关Retrofit 2的更多信息,请参阅: Retrofit — Getting Started and Create an Android Client
答案 1 :(得分:87)
我使用setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG"))
,它帮助了我
更新。
您也可以尝试将调试目的用作retrofit.client.Response
作为响应模型
答案 2 :(得分:30)
Retrofit 2.0.0-beta3更新
现在你必须使用okhttp3和builder。旧的拦截器也行不通。此响应是针对Android量身定制的。
这里有一个快速复制粘贴,包含新内容。
<强> 1。将您的gradle文件修改为
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile "com.squareup.retrofit2:converter-gson:2.0.0-beta3"
compile "com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3"
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
<强> 2。请查看以下示例代码:
使用新的导入。如果您不使用它,可以删除Rx,也可以删除您不使用的内容。
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.RxJavaCallAdapterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
public interface APIService {
String ENDPOINT = "http://api.openweathermap.org";
String API_KEY = "2de143494c0b2xxxx0e0";
@GET("/data/2.5/weather?appid=" + API_KEY) Observable<WeatherPojo> getWeatherForLatLon(@Query("lat") double lat, @Query("lng") double lng, @Query("units") String units);
class Factory {
public static APIService create(Context context) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(10, TimeUnit.SECONDS);
builder.connectTimeout(5, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(interceptor);
}
//Extra Headers
//builder.addNetworkInterceptor().add(chain -> {
// Request request = chain.request().newBuilder().addHeader("Authorization", authToken).build();
// return chain.proceed(request);
//});
builder.addInterceptor(new UnauthorisedInterceptor(context));
OkHttpClient client = builder.build();
Retrofit retrofit =
new Retrofit.Builder().baseUrl(APIService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
return retrofit.create(APIService.class);
}
}
}
<强>加成强>
我知道它的离场外观,但我发现它很酷。
如果未经授权的http错误代码,则此处是拦截器。我使用eventbus来传输事件。
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.androidadvance.ultimateandroidtemplaterx.BaseApplication;
import com.androidadvance.ultimateandroidtemplaterx.events.AuthenticationErrorEvent;
import de.greenrobot.event.EventBus;
import java.io.IOException;
import javax.inject.Inject;
import okhttp3.Interceptor;
import okhttp3.Response;
public class UnauthorisedInterceptor implements Interceptor {
@Inject EventBus eventBus;
public UnauthorisedInterceptor(Context context) {
BaseApplication.get(context).getApplicationComponent().inject(this);
}
@Override public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (response.code() == 401) {
new Handler(Looper.getMainLooper()).post(() -> eventBus.post(new AuthenticationErrorEvent()));
}
return response;
}
}
代码来自https://github.com/AndreiD/UltimateAndroidTemplateRx(我的项目)。
答案 3 :(得分:9)
似乎没有办法做基本+正文,但你可以使用FULL并过滤你不想要的标题。
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(syncServer)
.setErrorHandler(err)
.setConverter(new GsonConverter(gson))
.setLogLevel(logLevel)
.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"};
for (String bString : blacklist) {
if (msg.startsWith(bString)) {
return;
}
}
Log.d("Retrofit", msg);
}
}).build();
似乎在覆盖日志时,正文的前缀是类似于
的标记[ 02-25 10:42:30.317 25645:26335 D/Retrofit ]
所以通过调整自定义过滤器来记录基本+正文应该很容易。我正在使用黑名单,但也可以根据您的需要使用白名单。
答案 4 :(得分:3)
下面的代码适用于带有标题和无标题的打印日志请求&amp;响应。 注意:如果不使用标题,请注释.addHeader()行。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
//.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addNetworkInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
// .addHeader(Constant.Header, authToken)
.build();
return chain.proceed(request);
}
}).build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.baseUrl)
.client(client) // This line is important
.addConverterFactory(GsonConverterFactory.create())
.build();
答案 5 :(得分:2)
如果您使用的是Retrofit2和okhttp3,那么您需要知道Interceptor是按队列工作的。所以在你的其他拦截器之后添加loggingInterceptor:
var ajxobj = new XMLHttpRequest();
ajxobj.open('GET','sample.xml',false);
ajxobj.send();
var myobj = ajxobj.responseXML;
答案 6 :(得分:2)
我希望这段代码可以帮助您登录。<br/>
您只需要在Build.Gradle
中添加拦截器,然后使RetrofitClient
即可。
将此行添加到您的build.gradle
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
制作改造客户端
public class RetrofitClient {
private Retrofit retrofit;
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
private static RetrofitClient instance = null;
private static ApiServices service = null;
private static HttpLoggingInterceptor logging =
new HttpLoggingInterceptor();
private RetrofitClient(final Context context) {
httpClient.interceptors().add(new Interceptor() {
@Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder builder = originalRequest.newBuilder().
method(originalRequest.method(), originalRequest.body());
okhttp3.Response response = chain.proceed(builder.build());
/*
Do what you want
*/
return response;
}
});
if (BuildConfig.DEBUG) {
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// add logging as last interceptor
httpClient.addInterceptor(logging);
}
retrofit = new Retrofit.Builder().client(httpClient.build()).
baseUrl(Constants.BASE_URL).
addConverterFactory(GsonConverterFactory.create()).build();
service = retrofit.create(ApiServices.class);
}
public static RetrofitClient getInstance(Context context) {
if (instance == null) {
instance = new RetrofitClient(context);
}
return instance;
}
public ApiServices getApiService() {
return service;
}
}
RetrofitClient.getInstance(context).getApiService().yourRequestCall();
答案 7 :(得分:1)
ZoomX — Android Logger Interceptor是一个很好的拦截器,可以帮助您解决问题。
答案 8 :(得分:0)
对于android studio 3.0之前(使用android motinor)
https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses
https://www.youtube.com/watch?v=vazLpzE5y9M
对于android studio来自3.0及以上(使用android profiler作为android监视器被android profiler取代)
https://futurestud.io/tutorials/retrofit-2-analyze-network-traffic-with-android-studio-profiler
答案 9 :(得分:0)
答案 10 :(得分:0)
这不是最好的方法上面有更好的答案。这只是使用 Android 日志检查它的另一种方法。将它们全部放在这有助于捕获解析错误。
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
// Catching Responses From Retrofit
Log.d("TAG", "onResponseisSuccessful: "+response.isSuccessful());
Log.d("TAG", "onResponsebody: "+response.body());
Log.d("TAG", "onResponseerrorBody: "+response.errorBody());
Log.d("TAG", "onResponsemessage: "+response.message());
Log.d("TAG", "onResponsecode: "+response.code());
Log.d("TAG", "onResponseheaders: "+response.headers());
Log.d("TAG", "onResponseraw: "+response.raw());
Log.d("TAG", "onResponsetoString: "+response.toString());
}
@Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
Log.d("TAG", "onFailuregetLocalizedMessage: " +t.getLocalizedMessage());
Log.d("TAG", "onFailuregetMessage: " +t.getMessage());
Log.d("TAG", "onFailuretoString: " +t.toString());
Log.d("TAG", "onFailurefillInStackTrace: " +t.fillInStackTrace());
Log.d("TAG", "onFailuregetCause: " +t.getCause());
Log.d("TAG", "onFailuregetStackTrace: " + Arrays.toString(t.getStackTrace()));
Log.d("TAG", "getSuppressed: " + Arrays.toString(t.getSuppressed()));
}
});
答案 11 :(得分:0)
请在okHttpClient中添加Interceptor,以便在改造android中调用API时获取请求和响应日志
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(180, TimeUnit.SECONDS)
.writeTimeout(180, TimeUnit.SECONDS)
.connectTimeout(180, TimeUnit.SECONDS)
.addInterceptor(getLoggin())
.build();
public static HttpLoggingInterceptor getLoggin(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}