我正在使用retrofit2,我需要记录所有请求和响应。请求和响应工作完美,我只需要记录这些请求/响应,我尝试了几乎所有解决方案,我在这里找到,但没有找到解决方案。我不明白这里有什么问题
这是我的代码
class Factory {
private final static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static NetworkApi.Factory serverApi;
private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RequestApi.BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
public static NetworkApi getApi() {
if (BuildConfig.DEBUG){
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder()
.addHeader("Content-Type", "application/json");
return chain.proceed(builder.build());
}
});
httpClient.interceptors().add(interceptor);
}
if (serverApi == null){
serverApi = new NetworkApi.Factory();
}
return serverApi.retrofit.create(NetworkApi.class);
}
}
图书馆:
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
答案 0 :(得分:3)
尝试使用OkHttpClient,如下所示:
private OkHttpClient createDefaultOkHttpClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient().newBuilder()
.addInterceptor(interceptor)
.build();
}
然后将其设置为您的改造构建器:
Retrofit retrofitAsync = new Retrofit.Builder()
.baseUrl(BASE_URL_APPS)
.client(createDefaultOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(rxAdapter)
.build();
答案 1 :(得分:3)
像这样进行API调用。
ApiFactory.java
public interface LoginService {
/**
* To Post FormUrlEncoded to web service
*
* @return Call Object of Type JsonObject
*/
@FormUrlEncoded
@POST("api/login")
Call<JsonObject> login(@Field("email") String email,
@Field("password") String password,
@Field("devicetype") String devicetype,
@Field("deviceid") String deviceid);
}
}
LoginService接口
private void emailLoginRequest() {
LoginService loginService = ApiFactory.createService(LoginService.class);
Call<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
hideProgressDialog();
if (response.isSuccessful()) {
LOGD(TAG, "onResponse 0: " + response.body().toString());
LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class);
System.out.println("+++ get message >> " + loginResponse.getMessage());
int status = loginResponse.getStatus();
}else {
LOGD(TAG, "response fail 0: " + response.body());
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
hideProgressDialog();
LOGD(TAG, "onFailure: " + t.getMessage());
}
});
}
在此处进行API调用
public class LoginResponse {
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private Data data;
/**
* No args constructor for use in serialization
*
*/
public LoginResponse() {
Sample response model
// {
// "status": 1,
// "data": {
// "user_id": "565464564",
// "email": "email@email.com",
// "fullname": "james",
// "username": "james123",
// "country": "54654654",
// "city": "56546465546",
// "token": "dfgdfgdfg545465465464564"
// },
// "message": "Login successfull"
// }
}
/**
*
* @param message
* @param status
* @param data
*/
public LoginResponse(Integer status, String message, Data data) {
this.status = status;
this.message = message;
this.data = data;
}
/**
*
* @return
* The status
*/
public Integer getStatus() {
return status;
}
/**
*
* @param status
* The status
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
*
* @return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* @param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return The data
*/
public Data getData() {
return data;
}
/**
* @param data The data
*/
public void setData(Data data) {
this.data = data;
}
public class Data {
@SerializedName("user_id")
@Expose
private String userId;
@SerializedName("email")
@Expose
private String email;
/**
* No args constructor for use in serialization
*/
public Data() {
}
/**
* @param email
* @param userId
*/
public Data(String userId, String email) {
this.userId = userId;
this.email = email;
}
/**
* @return The userId
*/
public String getUserId() {
return userId;
}
/**
* @param userId The user_id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* @return The email
*/
public String getEmail() {
return email;
}
/**
* @param email The email
*/
public void setEmail(String email) {
this.email = email;
}
}
}
LoginResponse按照您的要求进行更改。
{{1}}
享受!
答案 2 :(得分:2)
我最好在使用Builder创建客户端时添加拦截器,如下面的代码。如果您注意到我们添加了两个拦截器 - 网络拦截器&gt; addNetworkInterceptor - 拦截器&gt; addInterceptor
主要区别是网络拦截器仅在存在真实请求(不从缓存加载)时才起作用。从网络或缓存加载的两种情况下的拦截器日志数据。
另外请确保您正在使用正确的BuildConfig(有时自动完成从您的某个库中导入它,然后它将始终为false)
`OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Logger networkLayerLogger = new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LogUtils.d("NetworkLayer", message);
}
};
HttpLoggingInterceptor.Logger appLayerLogger = new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LogUtils.d("ApplicationLayer", message);
}
};
HttpLoggingInterceptor networkLogging = new HttpLoggingInterceptor(networkLayerLogger);
HttpLoggingInterceptor appLogging = new HttpLoggingInterceptor(appLayerLogger);
networkLogging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
appLogging.setLevel(HttpLoggingInterceptor.Level.BODY);
clientBuilder.addNetworkInterceptor(networkLogging);
clientBuilder.addInterceptor(appLogging);
}
`