我想做的是发送一张图片到web服务器。当我在我的Android项目中调用一个方法时,我得到以下错误:找不到类'org.apache.http.entity.mime.content。Filebody',从方法com.example.tc.Send.send.
即使我有以下导入,也会发生这种情况:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
方法所在的类是这样的:
public class Send {
public Send(){
}
public static String send(String path) throws Exception {
String filePath = path;
String svar;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("path to web server");
FileBody pic = new FileBody(new File(filePath));
MultipartEntity requestEntity = new MultipartEntity();
requestEntity.addPart("file", pic);
httppost.setEntity(requestEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
svar = new String(responseBody);
System.out.println(svar);
} finally {
try {
httpclient.getConnectionManager().shutdown();
}
catch (Exception ignore) {
}
}
return svar;
}
}
谁能看出问题是什么吗?
添加这两个依赖
compile "org.apache.httpcomponents:httpcore:4.2.4"
compile "org.apache.httpcomponents:httpmime:4.3"
在类路径中需要有httpmime-4.0.jar。你可能(我猜你做)有这个jar到你的项目,但它是在运行时你的应用程序内?如果我理解正确的话,你可以从android应用程序中得到这个。你需要把这个jar放到android的类路径中。
-
添加依赖项:
<>之前编译的org.apache.httpcomponents: httpcore: 4.4.4"
从此链接http://hc.apache.org/downloads.cgi下载Apache HttpComponents jar文件,并在Android项目目录中创建一个/libs目录,并将jar文件复制到该目录中。点击Android项目的项目属性,然后选择Java Build Path settings,选择Libraries选项卡,点击add JAR按钮,选择/libs目录下的JAR,将其添加到项目中。
您还可以从Eclipse ADT包中获取这些文件,而不必单独下载它们—请参阅这里的答案:
https://stackoverflow.com/a/27906193/334402请注意,您将获得原始海报标记的错误,即"找不到类"。Filebody',如果您只是将外部JAR文件添加到构建路径中,但忘记将归档文件也导入到项目中。