How can I handle empty response body with Retrofit 2?

后端 未结 4 1888
悲&欢浪女
悲&欢浪女 2020-11-30 20:33

Recently I started using Retrofit 2 and I faced an issue with parsing empty response body. I have a server which responds only with http code without any content inside the

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 21:14

    Here is how I used it with Rx2 and Retrofit2, with PUT REST request: My request had a json body but just http response code with empty body.

    The Api client:

    public class ApiClient {
    public static final String TAG = ApiClient.class.getSimpleName();
    
    
    private DevicesEndpoint apiEndpointInterface;
    
    public DevicesEndpoint getApiService() {
    
    
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
    
    
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClientBuilder.addInterceptor(logging);
    
        OkHttpClient okHttpClient = okHttpClientBuilder.build();
    
        apiEndpointInterface = new Retrofit.Builder()
                .baseUrl(ApiContract.DEVICES_REST_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(DevicesEndpoint.class);
    
        return apiEndpointInterface;
    
    }
    

    The interface:

    public interface DevicesEndpoint {
     @Headers("Content-Type: application/json")
     @PUT(ApiContract.DEVICES_ENDPOINT)
     Observable sendDeviceDetails(@Body Device device);
    }
    

    Then to use it:

        private void sendDeviceId(Device device){
    
        ApiClient client = new ApiClient();
        DevicesEndpoint apiService = client.getApiService();
        Observable call = apiService.sendDeviceDetails(device);
    
        Log.i(TAG, "sendDeviceId: about to send device ID");
        call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }
    
            @Override
            public void onNext(ResponseBody body) {
                Log.i(TAG, "onNext");
            }
    
            @Override
            public void onError(Throwable t) {
                Log.e(TAG, "onError: ", t);
    
            }
    
            @Override
            public void onComplete() {
                Log.i(TAG, "onCompleted: sent device ID done");
            }
        });
    
    }
    

提交回复
热议问题