http://hc.apache.org/downloads.cgi
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
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.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class PostFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
File file = new File("c:/TRASH/zaba_1.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
遇到的问题:
自己搭建tomcat 使用 fileuploading 组件接受上传文件 Android 端使用httpclient 上传文件 使用代码
ContentBody cbFile = new FileBody(file, "image/jpeg");
服务器不能识别上传的是文件。 去掉 mimetype :
ContentBody cbFile = new FileBody(file);
则ok。 此代码如果服务器是java 测试无误。 php 服务器报文件类型不支持错误。
解决php 不支持类型:
mpEntity.addPart("userfile", file); 改为:
mpEntity.addPart("name", new InputStreamBody(new fileInputStread("path"), "image/jpeg", file.getName());
即 添加时候将文件换为文件输入流 (如果添加的是文件 会将文件数据一次加入内存然后一起发送, 如果是流则是边读边发送)