排球:MultipartRequest.getBody:IOException异常写入ByteArrayOutputStream [英] Volley: MultipartRequest.getBody: IOException writing to ByteArrayOutputStream
问题描述
我使用的排球为我的API调用。我需要张贴图片我断绝。
我试过很多MultipartRequest实施,无工作。
我只使用一个样本从<一试href="http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley/28144660?noredirect=1#comment50905173_28144660">How送的multipart / form-data的POST Android中与排球通过AZ _
不过,我得到MultipartRequest.getBody:IOException异常写入ByteArrayOutputStream错误
您可以帮助我在我的code,或知道用乱射请上传图像中的任何完整的样本。谢谢你。
进口java.io.ByteArrayOutputStream中;
进口的java.io.File;
进口java.io.FilterOutputStream中;
进口java.io.IOException异常;
进口java.io.OutputStream中;
进口java.io.UnsupportedEncodingException;
进口的java.util.HashMap;
进口的java.util.Map;
进口org.apache.http.HttpEntity;
进口org.apache.http.entity.ContentType;
进口org.apache.http.entity.mime.HttpMultipartMode;
进口org.apache.http.entity.mime.MultipartEntityBuilder;
进口org.apache.http.entity.mime.content.FileBody;
进口org.apache.http.util.CharsetUtils;
进口com.android.volley.AuthFailureError;
进口com.android.volley.NetworkResponse;
进口com.android.volley.Request;
进口com.android.volley.Response;
进口com.android.volley.VolleyLog;
// code。通过:
//http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley
// AZ_
//
/ **
*问题:E /截击:[17225] MultipartRequest.getBody:IOException异常写入ByteArrayOutputStream
* /
公共类MultipartRequest扩展请求&LT;字符串&GT; {
MultipartEntityBuilder实体= MultipartEntityBuilder.create();
HttpEntity httpentity;
私人字符串FILE_PART_NAME =文件;
私人最终Response.Listener&LT;字符串&GT; mListener;
私人最终文件mFilePart;
私人最终地图&LT;字符串,字符串&GT; mStringPart;
私人地图&LT;字符串,字符串&GT; headerParams;
私人最终MultipartProgressListener multipartProgressListener;
专用长文件长度= 0L;
公共MultipartRequest(字符串URL,Response.ErrorListener errorListener,
Response.Listener&LT;字符串&GT;监听器,文件的文件,长文件长度,
地图&LT;字符串,字符串&GT; mStringPart,
最终的地图&LT;字符串,字符串&GT; headerParams,字符串零件名称,
MultipartProgressListener progLitener){
超(Method.POST,网址,errorListener);
this.mListener =侦听器;
this.mFilePart =文件;
this.fileLength =文件长度;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME =零件名称;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
尝试 {
entity.setCharset(CharsetUtils.get(UTF-8));
}赶上(UnsupportedEncodingException E){
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
//公共无效addStringBody(字符串参数,字符串值){
//如果(mStringPart!= NULL){
// mStringPart.put(参数,值);
//}
//}
私人无效buildMultipartEntity(){
entity.addPart(FILE_PART_NAME,新FileBody(mFilePart,ContentType.create(图像/ GIF),mFilePart.getName()));
如果(mStringPart!= NULL){
对于(Map.Entry的&LT;字符串,字符串&GT;输入:mStringPart.entrySet()){
entity.addTextBody(entry.getKey(),entry.getValue());
}
}
}
@覆盖
公共字符串getBodyContentType(){
返回httpentity.getContentType()的getValue()。
}
@覆盖
公共字节[] getBody()抛出AuthFailureError {
ByteArrayOutputStream BOS =新ByteArrayOutputStream();
尝试 {
httpentity.writeTo(新CountingOutputStream(BOS,文件长度,multipartProgressListener));
}
赶上(IOException异常E){
VolleyLog.e(IOException异常写入ByteArrayOutputStream);
}
返回bos.toByteArray();
}
@覆盖
受保护的响应和LT;字符串&GT; parseNetworkResponse(NetworkResponse响应){
尝试 {
//的System.out.println(网络响应+新的String(response.data,UTF-8));
返回Response.success(新的String(response.data,UTF-8),
getCacheEntry());
}赶上(UnsupportedEncodingException E){
e.printStackTrace();
//他妈的它,它绝不应该发生,虽然
返回Response.success(新的字符串(response.data),getCacheEntry());
}
}
@覆盖
保护无效deliverResponse(字符串响应){
mListener.onResponse(响应);
}
//覆盖getHeaders(),如果你想要把东西在头
公共静态接口MultipartProgressListener {
无效转移(长转移,INT进度);
}
公共静态类CountingOutputStream扩展FilterOutputStream中的{
私人最终MultipartProgressListener progListener;
私人长期转移;
专用长文件长度;
公共CountingOutputStream(最终的OutputStream出来,长文件长度,
最后MultipartProgressListener监听器){
超(出);
this.fileLength =文件长度;
this.progListener =侦听器;
this.transferred = 0;
}
公共无效的write(byte []的B,诠释过,INT LEN)抛出IOException异常{
out.write(B,关闭,LEN);
如果(progListener!= NULL){
this.transferred + = LEN;
INT PROG =(int)的(转移* 100 /文件长度);
this.progListener.transferred(this.transferred,前卫);
}
}
公共无效的write(int b)在抛出IOException异常{
out.write(B);
如果(progListener!= NULL){
this.transferred ++;
INT PROG =(int)的(转移* 100 /文件长度);
this.progListener.transferred(this.transferred,前卫);
}
}
}
}
用户API类
公共无效uploadFile(字符串API,文件的文件,长文件长度,字符串零件名称,最终UserUploadSuccessListener监听器){
this.listener =侦听器;
字符串URL = Constant.DOMAIN + API;
地图&LT;字符串,字符串&GT; mHeaderParams =新的HashMap&LT;字符串,字符串&GT;();
mHeaderParams.put(婴儿车,pramValue);
MultipartRequest multipartRequest =新MultipartRequest
(URL,errorListener,新Response.Listener&LT;字符串&GT;(){
@覆盖
公共无效onResponse(字符串响应){
listener.onUserUploadFile(响应);
}
},文件,文件长度,空,mHeaderParams,零件名称,NULL);
multipartRequest.setRetryPolicy(新DefaultRetryPolicy(
30000,//30秒 - 改变你想要什么
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(multipartRequest);
}
然后调用它MainActivity:
私人无效的test1(){
档案文件=新的文件(路径:/storage/emulated/0/copy_folder/Magazine/images/assets/images/img_0007.jpg);
长文件长度= file.length();
新UserApi()。uploadFile(上传,文件,文件长度,imgPost,新UserApi.UserUploadSuccessListener(){
@覆盖
公共无效onUserUploadFile(字符串响应){
text.setText(uploadImage() - onUserUploadFile - &GT; \ñ+ response.toString());
}
@覆盖
公共无效onerror的(VolleyError错误){
text.setText(uploadImage() - 的onError - &GT; \ N+ error.toString());
}
@覆盖
公共无效onResponseError(字符串消息){
text.setText(uploadImage() - onResponseError - &GT; \ N+消息);
}
});
}
下面是我的机器人工作室的依赖:
相关性{
编译文件树(导演:库,包括:['的* .jar'])
编译com.android.support:appcompat-v7:22.2.0
编译com.google code.gson:GSON:2.3
编译com.mcxiaoke.volley:图书馆:1.0 +。
编译(org.apache.httpcomponents:httpmime:4.3.6'){
排除模块:HttpClient的
}
编译org.apache.httpcomponents:HttpClient的-安卓4.3.5
}
你有没有找到解决办法?如果没有,你可以在<一个有一个读我的回答href="http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley/31718902#31718902">How送的multipart / form-data的POST Android中与排球。我用 MultipartEntityBuilder
建部分。
如果不想使用HttpEntity因为德precation,请看看我的工作液<一href="http://stackoverflow.com/questions/32240177/working-post-multipart-request-with-volley-and-without-httpentity">Working POST multipart请求与排球和无HttpEntity 。
希望这有助于!
I am using Volley for my API call. I need to post a image to my sever.
I have tried many MultipartRequest implementation, None works.
I just tried using a sample from How to send a "multipart/form-data" POST in Android with Volley by AZ_.
But I get MultipartRequest.getBody: IOException writing to ByteArrayOutputStream Error.
Can you help me out on my code, or know any complete sample for uploading a image using Volley please. Thank you.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
//Code by:
//http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley
//AZ_
//
/**
* Problems : E/Volley﹕ [17225] MultipartRequest.getBody: IOException writing to ByteArrayOutputStream
*/
public class MultipartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "files";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
private Map<String, String> headerParams;
private final MultipartProgressListener multipartProgressListener;
private long fileLength = 0L;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, long fileLength,
Map<String, String> mStringPart,
final Map<String, String> headerParams, String partName,
MultipartProgressListener progLitener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.fileLength = fileLength;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME = partName;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
// public void addStringBody(String param, String value) {
// if (mStringPart != null) {
// mStringPart.put(param, value);
// }
// }
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
@Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity.writeTo(new CountingOutputStream(bos, fileLength, multipartProgressListener));
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
// System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// fuck it, it should never happen though
return Response.success(new String(response.data), getCacheEntry());
}
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
//Override getHeaders() if you want to put anything in header
public static interface MultipartProgressListener {
void transferred(long transfered, int progress);
}
public static class CountingOutputStream extends FilterOutputStream {
private final MultipartProgressListener progListener;
private long transferred;
private long fileLength;
public CountingOutputStream(final OutputStream out, long fileLength,
final MultipartProgressListener listener) {
super(out);
this.fileLength = fileLength;
this.progListener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (progListener != null) {
this.transferred += len;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
public void write(int b) throws IOException {
out.write(b);
if (progListener != null) {
this.transferred++;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
}
}
User API Class
public void uploadFile(String api, File file, long fileLength, String partName, final UserUploadSuccessListener listener) {
this.listener = listener;
String url = Constant.DOMAIN + api;
Map<String, String> mHeaderParams = new HashMap<String, String>();
mHeaderParams.put("pram", "pramValue");
MultipartRequest multipartRequest = new MultipartRequest
(url, errorListener, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
listener.onUserUploadFile(response);
}
}, file, fileLength, null, mHeaderParams, partName, null);
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(
30000, //30 seconds - change to what you want
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(multipartRequest);
}
Then Call it on MainActivity:
private void test1(){
File file = new File("path:/storage/emulated/0/copy_folder/Magazine/images/assets/images/img_0007.jpg");
long fileLength = file.length();
new UserApi().uploadFile("upload", file, fileLength, "imgPost", new UserApi.UserUploadSuccessListener() {
@Override
public void onUserUploadFile(String response) {
text.setText("uploadImage() - onUserUploadFile -> \n " + response.toString());
}
@Override
public void onError(VolleyError error) {
text.setText("uploadImage() - onError -> \n " + error.toString());
}
@Override
public void onResponseError(String message) {
text.setText("uploadImage() - onResponseError -> \n " + message);
}
});
}
Here are my dependencies in Android Studio:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.google.code.gson:gson:2.3'
compile 'com.mcxiaoke.volley:library:1.0.+'
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
}
Have you found the solution yet? If not, you can have a read at my answer at How to send a "multipart/form-data" POST in Android with Volley . I use MultipartEntityBuilder
to build the parts.
If don't wanna use HttpEntity because of deprecation, please take a look at my working solution Working POST Multipart Request with Volley and without HttpEntity.
Hope this helps!
这篇关于排球:MultipartRequest.getBody:IOException异常写入ByteArrayOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!