HttpClient发送post请求带参数实例

本例子跟上篇的get请求功能一致,只是换用了不同的请求实例,前端请求

var jsonParam = {
		title : title,
		partPath : partPath,
		modelId : modelId,
		exportTemplate : exportTemplate,
		officeCode : officeCode,
        orderNo : orderNo,
		currentUserId : currentUserId,
		newTitle : newTitle,
		exportFileType : exportFileType,
		
		fileType : fileType
	};
	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", "/uploadFile/getLuoHuoPaperDownLoad.do");
	var hiddenField = document.createElement("input");
	hiddenField.setAttribute("type", "hidden");
	hiddenField.setAttribute("name", "param");
	hiddenField.setAttribute("value", JSON.stringify(jsonParam));
	form.appendChild(hiddenField);
	document.body.appendChild(form);
	form.submit();

后端请求代码;

 /*
	 * 获取落货纸打印数据
	 */
	@RequestMapping(value = "getLuoHuoPaperDownLoad.do", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity getLuoHuoPaperDownLoad(HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
		ResponseEntity re = new ResponseEntity();
	HttpClient client = HttpClients.createDefault(); 

		//转译字符格式
	List<BasicNameValuePair> list = new ArrayList<>();
	BasicNameValuePair bn= new BasicNameValuePair("param",request.getParameter("param"));
	list.add(bn);
	String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list, "UTF-8"));

	//获取文件名
	String jsonResult = request.getParameter("param");
	JSONObject jsonObject = new JSONObject(jsonResult);
	String orderNo = jsonObject.getString("orderNo");

	String url = Config.get("url.llnQuery");
		if (!StringUtils.isBlank(url)) {
			url = url.substring(0, url.length()-17);

		}
		HttpPost post = new HttpPost(url+"/servlet/EcExportTemplateServlet");
		String json = JSON.serialize(paramsStr );
		if(!StringUtils.isEmpty(json)) {
			HttpEntity paramEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			post.setEntity(paramEntity); 
		}		
	HttpResponse responsecfs;
	responsecfs = client.execute(post );
	HttpEntity output = responsecfs.getEntity();
	
httpResponse.setHeader("Pragma", "public");
httpResponse.setHeader("Expires", "0");
httpResponse.setHeader("Cache-Control",
		"must-revalidate, post-check=0, pre-check=0");
httpResponse.setHeader("Content-Type", "application/force-download");
httpResponse.setHeader("Content-Disposition", "attachment;filename="+orderNo+".xls");
httpResponse.setContentType("text/html; charset=utf-8");
OutputStream outPut1 = httpResponse.getOutputStream();
output.writeTo(outPut1);
outPut1.flush();
outPut1.close();

return re;

}
这样就可以了,最后直接将文件流输出,记住,最后一定要关闭,这里重点只是将连接获取文件流,一般还得写上捕获异常,finally里面关闭文件流,一定得关闭,不然一致打开会造成服务器压力。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值