我如何处理Retrofit 2的空响应主体?

最近我开始使用Retrofit 2并且遇到了parsing空响应主体的问题。 我有一个服务器只响应与http代码没有任何内容的响应主体。 我怎样才能处理有关服务器响应的元信息(标题,状态码等)?

提前致谢!

编辑:

正如杰克·沃顿指出的那样,

 @GET("/path/to/get") Call<Void> getMyData(/* your args here */); 

是最好的方式去我的原始回应 –

您可以返回一个ResponseBody ,它将绕过parsing响应。

 @GET("/path/to/get") Call<ResponseBody> getMyData(/* your args here */); 

然后在你的电话里,

 Call<ResponseBody> dataCall = myApi.getMyData(); dataCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Response<ResponseBody> response) { // use response.code, response.headers, etc. } @Override public void onFailure(Throwable t) { // handle failure } }); 

如果您使用rxjava,请使用如下所示的内容:

 @GET("/path/to/get") Observable<Response<Void>> getMyData(/* your args here */); 

下面是我如何使用Rx2和Retrofit2,与PUT REST请求:我的请求有一个JSON正文,但只是空的正文http响应代码。

Api客户端:

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

界面:

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

然后使用它:

  private void sendDeviceId(Device device){ ApiClient client = new ApiClient(); DevicesEndpoint apiService = client.getApiService(); Observable<ResponseBody> call = apiService.sendDeviceDetails(device); Log.i(TAG, "sendDeviceId: about to send device ID"); call.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() { @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"); } }); } 
Interesting Posts