Android Retrofit 图片上传的最简单和明白的实现方式

RetrofitRequestHelper
.getInstance().getRetrofit(configChatRoomDataBean.getHttp())
.create(IRetrofitService.class)
.upload("/psr/files",getRequstBody(path))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread( ))
.as(bindLifecycle())
.subscribe(new ResponseObserver<>(new ResponseCallBack() {
@Override
public void onSuccess(UploadBean bean) {
if (bean.isStatus() || bean.getMsg().equals("success"))
getV().onUpload(bean.getImage());
}

@Override
public void onError(int code, String msg) {

}
}));

private RequestBody getRequstBody(String path) {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
Map parameters = new HashMap<>();
File file = new File(path);
MLog.e("==============file=="+file.getAbsolutePath());
parameters.put("file",file);
parameters.put("user_id", UserInfoManager.getInstance().getUserId());
Set keySet = parameters.keySet();
for (String key : keySet)
{
Object param = parameters.get(key);
if (param instanceof File)
{
File temfile = (File) param;
builder.addFormDataPart(key, temfile.getName(), RequestBody.create
(MediaType.parse("*/*"), temfile));
} else
{
String value = String.valueOf(param);
if(!StringUtils.isEmpty(value))
builder.addFormDataPart(key, value);
}
}
MLog.e("path=="+path);
return builder.build();
}

  该代码的真实链接如下:

      www.xxx.com/psr/files?file

 注意事项:

       请求回来的bean一定要写对,不然请求成功了,响应是200 但是你bean中没有任何数据.我曾经就踩过这个坑.就因为后台临时改了bean,又没有更新文档,结果响应成功了,就是没有数据出来!   

你可能感兴趣的:(安卓,安卓Bug,安卓新技术)