更新时间:2023-01-15 13:31:31
public class CustomMultiRequest extends Request<JSONObject> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "postfieldname[]";
private final Response.Listener<JSONObject> mListener;
private final ArrayList<File> mFilePart;
private final ArrayList<PostEntityModel> mStringPart;
public CustomMultiRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener,ArrayList<File> files, ArrayList<PostEntityModel> stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = files;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
for (File file : mFilePart){
entity.addPart(FILE_PART_NAME, new FileBody(file));
}
try
{
for(PostEntityModel postEntityModel : mStringPart){
entity.addPart(postEntityModel.getName(), new StringBody(postEntityModel.getValue()));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
{
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response)
{
mListener.onResponse(response);
}
}
如果使用Gradle,请将其添加到build.gradle文件中:
If you use Gradle, add this to your build.gradle file:
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'