1

我正在使用最新版本的改造,retrofit2,v2.0.0-beta3。API 响应是用户对象或空响应(空值)。如果我发送正确的用户名/密码,则句柄将进入 onResponse 方法并使用成功的 User 对象。但是,如果发送错误的密码,那么 API 将不会返回任何内容,响应标头中的值很少。但是我在 onFailure(Throwable) 中遇到了MalformedJsonException 。

“com.google.gson.stream.MalformedJsonException:使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON”

这是错误的屏幕截图, 在此处输入图像描述

我认为应该有某种方式来处理空响应和读取响应标头,使用 ResponseInceptor 或自定义回调。但不知道如何使用它。

这是代码,

// 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());
    }

});
4

2 回答 2

1

您需要为 Retrofit 提供一个 GSON 实例。

尝试:

Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(baseURL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(client)
    .build();
于 2016-01-08T15:02:39.000 回答
0

您是否已将 'com.squareup.retrofit2:converter-gson:2.0.0-beta3' 添加到 gradle 依赖项中?

你可以像这样创建一个 Retrofit 实例:

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;
}

对于标头,另一种添加方式,例如您要添加的“授权”标头,只需在您的 api 端点接口中添加一个名为 @Header 的注释,用于 API 调用,该标头是必需的

例子:

    @POST("/login/")
    Call<Farm> login(@Header("Authorization") String token, @Body User user);
于 2016-01-27T11:58:42.107 回答