在大家使用网络请求的时候,往往会出现一种情况:需要拿到服务器返回来的JSON字符串,而Retrofit会默认将Json解析,而又没有直接暴露出拿到Json字符串的方法;
今天测接口的时候,发现当数据正常时,服务器会返回{"code":200,"datas":"1"},当请求参数有错误时,会返回{"code":400,"datas":{"error":"u59d3u540du4e0du80fdu4e3au7a7a"}},datas里一会儿是字符串,一会儿是对象,这时就不能用JAVABEAN的形式接收返回数据了。
示例:
//删除地址 @FormUrlEncoded @POST(ServiceAddr.ADDR_DEL_URL) Observable<ResponseBody> delAddr(@FieldMap HashMap<String,String> map);
或
//删除地址 @FormUrlEncoded @POST(ServiceAddr.ADDR_DEL_URL) Call<ResponseBody> delAddr2(@FieldMap HashMap<String,String> map);
Presenter层:
public void delAddr(String baseUrl,HashMap<String,String> map){ addrManageModel.delAddr(baseUrl, map) .subscribe(new Subscriber<ResponseBody>() { @Override public void onCompleted() { Logger.t(TAG).d("地址删除成功"); } @Override public void onError(Throwable e) { Logger.t(TAG).d("地址删除失败"+e.getMessage()); } @Override public void onNext(ResponseBody responseBody) { BufferedSource source = responseBody.source(); try { source.request(Long.MAX_VALUE); // Buffer the entire body. } catch (IOException e) { e.printStackTrace(); } Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if(contentType != null){ charset = contentType.charset(UTF8); //获取Response的body的字符串 并打印 Logger.t(TAG).d(buffer.clone().readString(charset)); addrManageView.delAddrShow(buffer.clone().readString(charset)); } } }); }
或者
public void delAddr2(String baseUrl,HashMap<String,String> map){ addrManageModel.delAddr2(baseUrl, map).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { Logger.t(TAG).d(response.body().toString()+"===="+response.message()+"==="+response.code()); BufferedSource source = response.body().source(); try { source.request(Long.MAX_VALUE); // Buffer the entire body. } catch (IOException e) { e.printStackTrace(); } Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = response.body().contentType(); if(contentType != null){ charset = contentType.charset(UTF8); //获取Response的body的字符串 并打印 Logger.t(TAG).d(buffer.clone().readString(charset)); addrManageView.delAddrShow(buffer.clone().readString(charset)); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); }
在页面上调用:
delAddrShow()更新UI即可。