HttpClient傳送post請求帶引數例項
阿新 • • 發佈:2018-12-28
本例子跟上篇的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(); return re;
}
這樣就可以了,最後直接將檔案流輸出