在我的 android 项目中,我将zip文件上传到服务器 HTTP post request 。在这种情况下,我使用 httpcore 和 httpmime 库。我正在使用 AsyncTask 进行上传。 AsyncTask的doInBackground方法如下,
@Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
builder.addPart("name", stringBody);
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
代码编译,运行。但当上传任务继续不上传该文件时,日志会显示按摩。
05-03 14:29:00.223 27471-27687/com.x.l D/dalvikvm: DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
05-03 14:29:00.223 27471-27687/com.x.l W/dalvikvm: VFY: unable to resolve static field 44070 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
05-03 14:29:00.223 27471-27687/com.x.l D/dalvikvm: VFY: replacing opcode 0x62 at 0x001b
05-03 14:29:00.233 27471-27687/com.x.l D/dalvikvm: DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
05-03 14:29:00.233 27471-27687/com.x.l W/dalvikvm: VFY: unable to resolve static field 44065 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;
05-03 14:29:00.233 27471-27687/com.x.l D/dalvikvm: VFY: replacing opcode 0x62 at 0x0015
但它没有提供任何错误。所以我花了很多时间试图弄清楚它并没有成功。
我的build.gradle文件中的依赖项如下所示,
dependencies {
compile project(':volley')
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:multidex:'
compile 'org.apache.httpcomponents:httpcore:4.4.4'
compile'org.apache.httpcomponents:httpmime:4.3.6'
}
Editted ....... 根据stac答案,我编辑了我的代码并添加了以下两部分
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + boundary);
和
builder.setBoundary(boundary);
所以现在我的最终代码是这样的。
@Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + boundary);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setBoundary(boundary);
FileBody fileBody = new FileBody(new File(filePath));
StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
builder.addPart("name", stringBody);
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
所以现在它没有显示我上面提到的错误。但仍然没有上传文件。 我的代码有什么问题。有人建议我可以解决这个问题。谢谢和问候!
答案 0 :(得分:0)
我使用凌空库上传文件。
希望这段代码可以帮到你。
这是我用来请求服务器的类。
public class OnPostNewtRequest扩展JsonRequest { MultipartEntityBuilder entity = MultipartEntityBuilder.create(); HttpEntity httpentity; 私人最终的Response.Listener mListener; private file mFilePart = null; private file mFileVideos = null; private final Map mStringPart;
public OnPostNewtRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener, File file, File fileVideos, Map<String, String> mStringPart) { super(Method.POST, url, null, listener, errorListener); mListener = listener; mFilePart = file; mFileVideos = fileVideos; this.mStringPart = mStringPart; entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); buildMultipartEntity(); } public void addStringBody(String param, String value) { mStringPart.put(param, value); } private void buildMultipartEntity() { if (mFileVideos != null) entity.addBinaryBody(Constant.KEY_FILE_VIDEO, mFileVideos, ContentType.create("video/mp4"), mFileVideos.getName()); if (mFilePart != null) entity.addBinaryBody(Constant.KEY_FILE, mFilePart, ContentType.create("image/jpeg"), mFilePart.getName()); for (Map.Entry<String, String> entry : mStringPart.entrySet()) { try { entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.defaultCharset())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public String getBodyContentType() { return httpentity.getContentType().getValue(); } @Override public byte[] getBody() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { httpentity = entity.build(); httpentity.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); }
}
以及如何使用此请求
1。首先你使用
Map params = new HashMap();
添加&#34;键&#34;和params的值示例:params.put(Constant.KEY_WORD,mTag);.
第2步。
OnPostNewtRequest multipartRequest = new OnPostNewtRequest(Constant.URL_UP_POST,new Response.ErrorListener(){ @覆盖 public void onErrorResponse(VolleyError error){ if(mAction!= null){ mAction.onError(误差); } 解雇(); error.printStackTrace(); } 新的Response.Listener(){ @覆盖 public void onResponse(JSONObject response){
}
}, linkFileImage, fileVideos, params);
YourApplication.getInstance().addToRequestQueue(multipartRequest);
希望这能帮到你。