HttpClient的使用,java代码发送http请求文件


//java代码发http请求
public void sendHttpRequest(String selfIpPort, String filePath) throws Exception{

List<String> ipPortList = customerLoginService.queryIpPortList(selfIpPort);
for (Iterator iterator = ipPortList.iterator(); iterator.hasNext();) {
String ipPort = (String) iterator.next();
String urlStr = "http://"+ipPort+"/TAWM/fileDownload/electronicContractPart/getFile";
//注意权限的拦截, 得不到数据可能是因为url被权限拦截。
HttpClient httpClient = HttpUtil.getHttpClient();
PostMethod post = new PostMethod(urlStr);
NameValuePair[] valuePairs = new NameValuePair[1];
valuePairs[0] = new NameValuePair("filePath", filePath);
post.addParameters(valuePairs);

int ret = httpClient.executeMethod(post);
log.debug("HTTP状态:" + ret);
if(ret != 200){
String[] ipPortArr = ipPort.split(":");
customerLoginService.updateServerStatus(ipPortArr[0], ipPortArr[1]);
return ;
}

InputStream inputStream = post.getResponseBodyAsStream();

FileOutputStream fos = new FileOutputStream(filePath);

byte buffer[] = new byte[2048];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
while((len=inputStream.read(buffer))>0){
//输出缓冲区的内容到浏览器,实现文件下载
fos.write(buffer, 0, len);
}
fos.close();
inputStream.close();
}
}


//响应http请求
@RequestMapping("/electronicContractPart/getFile")
public void getFileBytes(HttpServletRequest request, HttpServletResponse response){
try {
String filePath = request.getParameter("filePath");

if(!new File(filePath).exists()){
return ;
}
//读取要下载的文件
FileInputStream in = new FileInputStream(filePath);
//创建缓冲区
byte buffer[] = new byte[2048];
OutputStream outputStream = response.getOutputStream();
int len = 0;
while((len=in.read(buffer))>0){
outputStream.write(buffer, 0, len);
}
outputStream.flush();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值