java httpclient 文件上传

是网上的例子, 用过就记录下来了



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.ParseException;
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 UploadTest {

// file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
public void SubmitPost(String url, String filename1, String filepath) {

HttpClient httpclient = new DefaultHttpClient();

try {
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
StringBody comment = new StringBody("aaa");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", bin);// file1为请求后台的File upload;属性
reqEntity.addPart("name", comment);// filename1为请求后台的普通参数;属性
httppost.setEntity(reqEntity);
// 后台以ajax方式处理
httppost.setHeader("X-Requested-With", "XMLHttpRequest");
HttpResponse response = httpclient.execute(httppost);

int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode: " + statusCode);
if (statusCode == HttpStatus.SC_OK) {
System.out.println("服务器正常响应.....");
HttpEntity resEntity = response.getEntity();
System.out.println(EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据
System.out.println(resEntity.getContent());
EntityUtils.consume(resEntity);
}

} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {

}
}
}

/**
* @param args
*/
public static void main(String[] args) {
UploadTest httpPostArgumentTest2 = new UploadTest();
httpPostArgumentTest2.SubmitPost("http://localhost:8080/maintenance/repair-mans/importing/upload", "a.xls", "E:");
}

}




<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.1.2</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值