我要做的是将图片发送到网络服务器。当我在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;
}
}
任何人都可以看到问题所在吗?
答案 0 :(得分:5)
添加这两个依赖
compile "org.apache.httpcomponents:httpcore:4.2.4"
compile "org.apache.httpcomponents:httpmime:4.3"
答案 1 :(得分:4)
您需要在类路径中使用httpmime-4.0.jar。您可以(我猜你这样做)将这个jar放到你的项目中,但它是否在你的应用程序中运行时? 如果我理解正确你从Android应用程序得到这个。你需要在你的android的类路径中拥有这个jar。
答案 2 :(得分:0)
从此链接http://hc.apache.org/downloads.cgi下载Apache HttpComponents jar文件,并在Android项目目录中创建/ libs目录,并将JAR文件复制到该目录。通过单击Android项目的Project属性将其添加到项目中,然后选择Java Build Path设置,选择Libraries选项卡并单击Add JAR按钮并选择/ libs目录中的jar。
答案 3 :(得分:0)
您也可以从Eclipse ADT包中获取这些文件而无需单独下载 - 请参阅此处的答案:
https://stackoverflow.com/a/27906193/334402
请注意,如果您只是将外部JAR文件添加到构建路径,那么您将收到标记原始海报的错误,即“找不到类”org.apache.http.entity.mime.content.Filebody'。忘记将档案导入您的项目。
答案 4 :(得分:0)
添加依赖项:
compile 'org.apache.httpcomponents:httpcore:4.4.4'