632
技术社区[云栖]
HttpClient4 文件上传
httpclient上传文件实际上就是模拟一个http的表单提交请求。- package test.httpclient4;
- import java.io.File;
- import java.io.IOException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.ClientProtocolException;
- 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.entity.mime.content.StringBody;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- public class SendFile {
- public static void main(String[] args) throws ClientProtocolException,
- IOException {
- HttpClient httpclient = new DefaultHttpClient();
- //请求处理页面
- HttpPost httppost = new HttpPost(
- "https://localhost:8080/webtools/upload.jsp");
- //创建待处理的文件
- FileBody file = new FileBody(new File("d:/22.rar"));
- //创建待处理的表单域内容文本
- StringBody descript = new StringBody("0431.la");
- //对请求的表单域进行填充
- MultipartEntity reqEntity = new MultipartEntity();
- reqEntity.addPart("file", file);
- reqEntity.addPart("descript", descript);
- //设置请求
- httppost.setEntity(reqEntity);
- //执行
- HttpResponse response = httpclient.execute(httppost);
- //HttpEntity resEntity = response.getEntity();
- //System.out.println(response.getStatusLine());
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- HttpEntity entity = response.getEntity();
- //显示内容
- if (entity != null) {
- System.out.println(EntityUtils.toString(entity));
- }
- if (entity != null) {
- entity.consumeContent();
- }
- }
- }
- }
这里说明一下 需要一个额外的包,apache 的mime4j 的lib。
最后更新:2017-04-03 22:30:58