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();
		}
	}

猜你喜欢

转载自2018scala.iteye.com/blog/2221645