我试图通过拦截使用OkHttp来登录Crashlytics,因为我的一些客户遇到500错误,并且我想完成有关他们发布的内容并获得响应的详细信息。就像OkHttp在Android Studio的日志中显示的一样。
当发生200错误但未成功时,我尝试记录详细信息。
@Module
public class DIModule {
MyApplication application;
public DIModule(MyApplication application) {
this.application = application;
}
public DIModule()
{
}
@Singleton
@Provides
OkHttpClient getOkHttpClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.addInterceptor(logging).addInterceptor(new HeaderInterceptor())
.build();
}
@Singleton
@Provides
Retrofit getRetro(OkHttpClient client) {
return new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@Singleton
@Provides
Context provideApplicationContext()
{
return application;
}
@Singleton
@Provides
MSharedPref getSharedPreferences(Context app)
{
return new MSharedPref(app);
}
class HeaderInterceptor implements Interceptor
{
@Override
public Response intercept(Chain chain) throws IOException
{
Request.Builder builder = chain.request().newBuilder();
String token="No Value";
if(StaticData.loginResponse!=null)
token=StaticData.loginResponse.getAccess_token();
builder.header("Authorization", "Bearer "+ token)
.header("Accept", "application/json")
.header("Content-Type", "application/json");
Response response=chain.proceed(builder.build());
if(response.code()==200)
{
Log.d("test67","ooooooooooooooooooo"+response);
//here I will log
}
return response;
}
}
}
Log.d()正在显示响应{协议= http / 1.1,代码= 200,消息=确定,URL = http://........./api/user}
到crashlytics。
我将从响应中获取所有OkHttp日志,还是我走错了路。通过Crashlytics.logException(e);
记录非致命事件也只需要Throwable。那我该怎么做?
请帮助..
这是我为解决此问题所做的工作。首先,我创建了一个自定义日志记录异常,该异常接受一个名为CustomLoggingException
的请求对象,并且仅使用该请求对象作为String来调用异常主构造函数。
我也将主体作为字符串传递,因为您将遇到请求字符串不记录主体内容而只记录对象类型的问题。public class CustomLoggingException extends Exception { public CustomLoggingException(Request builderRequest, String body) { super(builderRequest.toString() + body); }}
[Note
So
我正在检查主体是否不为null,然后获取其String内容。if (builderRequest.body() != null) body = stringifyRequestBody(builderRequest.body());
和将使您的身体成为String的stringifyRequestBody函数
private String stringifyRequestBody(RequestBody body) { try { BufferedSink buffer = new Buffer(); body.writeTo(buffer); return buffer.getBuffer().readUtf8(); } catch (Exception e) { Logger.d("Failed to stringify request body: " + e.getMessage()); return ""; } }
之后,您只需使用这两个输入将异常记录到Crashlytics,就可以>
Crashlytics.logException(new CustomLoggingException(builderRequest, body));