I try to upload data to server, my data containing multiple images and large JSON, before it, I Try to send with convert image to string using base64 and send my another data and image that I’ve convert before with JSON, but I face Problem OutOfMemory here, so I read one of solutions that said I must to try using MultipartEntityBuilder. I still confusing and not understand how to do it with MultiPartEntityBuilder, Is there anyone can help me the way to do it with MultiPartEntityBuilder?
To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
//Image attaching
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());
//Json string attaching
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));
Then make request as usual:
HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();
利用volley时,新建MultipartRequest,如下:
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.entity.ContentType;
import ch.boye.httpclientandroidlib.entity.mime.HttpMultipartMode;
import ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder;
import com.android.volley.*;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class MultipartRequest extends Request<String> {
private static final String TAG ="MultipartRequest" ;
protected static final String PROTOCOL_CHARSET = ResourceUtils.getString(R.string.default_charset);
// private MultipartEntity entity = new MultipartEntity();
MultipartEntityBuilder mEntity = MultipartEntityBuilder.create();
HttpEntity mHttpentity;
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
if (mFilePart != null) {
LogCus.d(TAG, "img-path>>" + file.getAbsolutePath());
LogCus.d(TAG, "img-name>>" + file.getName());
}
this.mStringPart = mStringPart;
mEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
if (mStringPart != null) {
mStringPart.put(param, value);
} else {
throw new IllegalArgumentException("创建multipartrequest时并未初始化mStringPart,则不予后期添加数据");
}
}
private void buildMultipartEntity() {
//NOTE: 1、添加图片
if (mFilePart != null) {
// mEntity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
mEntity.addBinaryBody(FILE_PART_NAME, mFilePart, ContentType.create("image/png"), mFilePart.getName());
}
//NOTE: 2、添加字符串部分--转化成utf-8编码
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
try {
mEntity.addBinaryBody(entry.getKey(), entry.getValue().getBytes(PROTOCOL_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
@Override
public String getBodyContentType() {
return mHttpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpentity = mEntity.build();
mHttpentity.writeTo(bos);
} catch (IOException e) {
e.printStackTrace();
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
LogCus.d(TAG, jsonString);
return Response.success(jsonString, getCacheEntry());
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}