我正在使用最新版本的retrofit,retrofit2,v2.0.0-beta3。 API响应是User对象或空响应(null值)。如果我发送了正确的用户名/密码,那么handle会使用成功的User对象进入onResponse方法。但是如果发送错误的密码,则API将不返回任何内容,响应头中的值很少。但是我在onFailure(Throwable)中得到 MalformedJsonException 。
“com.google.gson.stream.MalformedJsonException:使用JsonReader.setLenient(true)接受第1行第1行路径中格式错误的JSON $”
我认为应该使用ResponseInceptor或Custom CallBack来处理null响应并读取响应头。但不知道我怎么能用它。
这是代码,
// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("Authorization", new ITAuthorizationUtil().getAuthorization(user.getMobile_no(), user.getPassword())).build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
ITAPIEndpointsInterface apiEndpointsInterface = retrofit.create(ITAPIEndpointsInterface.class);
///
Call<User> call = apiEndpointsInterface.userLogin(senderId, applicationId, registrationId);
//asynchronous call
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response) {
ApiResponse apiResponse = ITAPIStatusInfo.getApiErrorObject_Retrofit(response.headers());
onSuccess( response.body(),apiResponse);
}
@Override
public void onFailure(Throwable t) {
Log.d(">>> ",t.getMessage());
}
});
答案 0 :(得分:1)
您需要为Retrofit提供GSON实例。
尝试:
Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
答案 1 :(得分:0)
您是否已添加&#39; com.squareup.retrofit2:converter-gson:2.0.0-beta3&#39;以获取gradle依赖项?
你可以像这样创建一个Retrofit实例:
df <- sapply(df, function(x) x - c(10, 5))
x y
[1,] 0 -5
[2,] 5 0
[3,] 0 -5
[4,] 5 0
[5,] 0 -5
[6,] 5 0
[7,] 0 -5
[8,] 5 0
[9,] 0 -5
[10,] 5 0
对于标题,另一种添加方式如此&#34;授权&#34;你要添加的标题,只需在api端点接口中添加一个名为@Header的Annotation,用于API调用,标题是必需的
示例:
private static MyClient MyClient;
public static String baseUrl = "http://mybaseurl.com" ;
public static MyClient getClient() {
if (MyClient == null) {
OkHttpClient httpClient = new OkHttpClient();
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
//.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
MyClient = client.create(MyClient.class);
}
return MyClient;
}