本文目录
一、添加依赖
二、代码
服务器的接收可参考SpingBoot上传文字与文件
一、添加依赖
// 阿里巴巴的json序列化工具
implementation 'com.alibaba:fastjson:1.2.56'
// okhttp
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
//Rxjava 和 Retrofit
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation "io.reactivex.rxjava2:rxjava:2.2.8"
二、代码
1、RespEntity
/**
* 网络请求响应的结果
*/
public class RespEntity
{
private boolean isSuccess;
private String msg;
private Object data;
public boolean isSuccess()
{
return isSuccess;
}
public void setSuccess(boolean success)
{
isSuccess = success;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public Object getData()
{
return data;
}
public void setData(Object data)
{
this.data = data;
}
@Override
public String toString()
{
return "isSuccess:" + isSuccess + "; msg:" + msg + "; data:" + data;
}
}
2、IUploadMultipart
实际使用中,如果泛型为RespEntity
,则解析的布尔值一直为false,因此用JSONObject
,然后在服务器响应时再进行转换。
import com.alibaba.fastjson.JSONObject;
import com.shufeng.communitymanage.base.bean.RespEntity;
import com.shufeng.communitymanage.base.constvar.NetworkConst;
import java.util.List;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
/**
* 参考 https://www.jb51.net/article/120237.htm
* 实际使用中,如果泛型为RespEntity,则解析的布尔值一直为false
*/
public interface IUploadMultipart
{
// retrofit + rxjava
@Multipart
@POST(NetworkConst.SHOP_ADD_URI)
Observable postTextAndPhoto(@PartMap Map map, @Part List parts);
// retrofit
@Multipart
@POST(NetworkConst.SHOP_ADD_URI)
Call postTextAndPhoto2(@PartMap Map map, @Part List parts);
}
3、调用
private void upload()
{
activityHelper.showLoadingDialog();
Map params = new HashMap<>();
//以下参数是伪代码,参数需要换成自己服务器支持的
params.put("type", convertToRequestBody("type"));
params.put("title", convertToRequestBody("title"));
params.put("info", convertToRequestBody("info"));
params.put("count", convertToRequestBody("count"));
//为了构建数据,同样是伪代码
List fileList = getFileList();
List partList = filesToMultipartBodyParts(fileList);
retrofitRequest(params, partList);
}
private void retrofitRequest(Map map, List parts)
{
HttpRequestClient.getRetrofitHttpClient().create(IUploadMultipart.class)
.postTextAndPhoto(map, parts)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer()
{
@Override
public void onSubscribe(@NonNull Disposable d)
{
// ALog.d("onSubscribe");
}
@Override
public void onNext(@NonNull JSONObject pResp)
{
try
{
RespEntity _Result = JSON.toJavaObject(pResp, RespEntity.class);
if (_Result.isSuccess())
{
activityHelper.showToast("添加成功");
}
else
{
activityHelper.showToast("添加失败:" + _Result.getMsg());
}
}
catch (Exception ex)
{
ex.printStackTrace();
activityHelper.showToast("数据解析失败:" + ex.getMessage());
}
}
@Override
public void onError(@NonNull Throwable e)
{
e.printStackTrace();
ALog.d("onError");
activityHelper.showToast("失败:" + e.getMessage());
activityHelper.hideLoadingDialog();
}
@Override
public void onComplete()
{
// ALog.d("onComplete");
activityHelper.hideLoadingDialog();
}
});
}
private RequestBody convertToRequestBody(String param)
{
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
return requestBody;
}
private List filesToMultipartBodyParts(List files)
{
List parts = new ArrayList<>(files.size());
for (File file : files)
{
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png,image/jpg"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFiles", file.getName(), requestBody);
parts.add(part);
}
return parts;
}