在我的Android项目中,我使用MultipartEntityBuilder使用AsyncTask将文件上传到后端。我在我的project.my doInBackground方法中使用httpmime-4.5.2上传AsyncTask如下所示。
@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 entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
entity.addPart("file", fileBody);
HttpEntity entity_ = entity.build();
httpPost.setEntity(entity_);
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;
}
}
但是当AsyncTask正在执行时,它会给我以下错误。
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1912)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1884)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
所以这段代码有什么问题。我怎样才能解决这个问题。谢谢和问候。
答案 0 :(得分:3)
最后我弄明白了原因。我已将httpmime库导入到项目中。但在我的情况下,它需要与httpmime一起执行另一个库。我导入httpcore库并构建项目。它解决了这个问题。 :D我只需将以下行添加到build.gradle并重新构建项目。
compile 'org.apache.httpcomponents:httpcore:4.4.4'