简体   繁体   中英

how to handle response with retrofit2 (v2.0.0-beta3)

I am using latest version of retrofit, retrofit2, v2.0.0-beta3. The API response is either User object or empty response(null value). If I send correct username/password then handle goes in onResponse method with successful User object. But if send wrong password then the API will return nothing, with few values in response headers. But I am getting MalformedJsonException in onFailure(Throwable).

"com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $"

here is screenshot of error, 在此处输入图片说明

I think there should be someway to handle null response and to read response headers, using ResponseInceptor or Custom CallBack. But dont know how I can use this.

here is the code,

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

});

You need to provide a GSON instance to Retrofit.

Try:

Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(baseURL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(client)
    .build();

Have you added 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'to gradle dependencies?

Than you can just create a instance of Retrofit like this:

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

And for headers, another way of adding like this "Authorization" header that you are adding, it is just add in your api endpoints interface a Annotation called @Header for the API calls which a header is necessary

Example:

    @POST("/login/")
    Call<Farm> login(@Header("Authorization") String token, @Body User user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM