我试图通过拦截使用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}
崩溃分析。
我将从响应中获取所有OkHttp日志,还是我走错了路。由Crashlytics.logException(e);
记录为非致命事件也只需要Throwable。那我该怎么做?
请帮助。
答案 0 :(得分:0)
这是我为解决此问题所做的工作。
首先,我创建了一个自定义日志记录异常,该异常接受一个名为CustomLoggingException
的请求对象,并且只调用该请求对象为String的异常主构造函数
public class CustomLoggingException extends Exception {
public CustomLoggingException(Request builderRequest, String body) {
super(builderRequest.toString() + body);
}}
请注意,我也将主体作为字符串传递,因为您将遇到请求字符串不记录主体内容而只记录对象类型的问题。
所以,我正在检查正文,如果它不为null,则获取其String内容。
if (builderRequest.body() != null)
body = stringifyRequestBody(builderRequest.body());
和stringifyRequestBody函数,它将使您的身体成为String
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));
答案 1 :(得分:0)