您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇内容主要讲解“HttpClient远程请求struts2的文件流并实现下载的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“HttpClient远程请求struts2的文件流并实现下载的方法”吧!
HttpClientUtil工具类:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class HttpClientUtil { private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); /** * 封装HTTP POST方法 * * @param * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String post(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpPost.setConfig(requestConfig); List<NameValuePair> formparams = setHttpParams(paramMap); UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8"); httpPost.setEntity(param); HttpResponse response = httpClient.execute(httpPost); // logger.info("************{}", response); String httpEntityContent = getHttpEntityContent(response); // logger.info("************{}", httpEntityContent); httpPost.abort(); // logger.info("************{}", httpEntityContent); return httpEntityContent; } /** * 封装HTTP POST方法 * * @param * @param * @return * @throws ClientProtocolException * @throws IOException */ public static HttpResponse postForResponse(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpPost.setConfig(requestConfig); List<NameValuePair> formparams = setHttpParams(paramMap); UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8"); httpPost.setEntity(param); HttpResponse response = httpClient.execute(httpPost); return response; } /** * 封装HTTP POST方法 * * @param * @param (如JSON串) * @return * @throws ClientProtocolException * @throws IOException */ public static String post(String url, String data) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/json; charset=utf-8"); httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8"))); HttpResponse response = httpClient.execute(httpPost); String httpEntityContent = getHttpEntityContent(response); httpPost.abort(); return httpEntityContent; } /** * 封装HTTP GET方法 * * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String get(String url) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpGet.setConfig(requestConfig); httpGet.setURI(URI.create(url)); HttpResponse response = httpClient.execute(httpGet); String httpEntityContent = getHttpEntityContent(response); httpGet.abort(); return httpEntityContent; } /** * 封装HTTP GET方法 * * @param * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String get(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpGet.setConfig(requestConfig); List<NameValuePair> formparams = setHttpParams(paramMap); String param = URLEncodedUtils.format(formparams, "UTF-8"); httpGet.setURI(URI.create(url + "?" + param)); HttpResponse response = httpClient.execute(httpGet); String httpEntityContent = getHttpEntityContent(response); httpGet.abort(); return httpEntityContent; } /** * 封装HTTP PUT方法 * * @param * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String put(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpPut.setConfig(requestConfig); List<NameValuePair> formparams = setHttpParams(paramMap); UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8"); httpPut.setEntity(param); HttpResponse response = httpClient.execute(httpPut); String httpEntityContent = getHttpEntityContent(response); httpPut.abort(); return httpEntityContent; } /** * 封装HTTP DELETE方法 * * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String delete(String url) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpDelete.setConfig(requestConfig); httpDelete.setURI(URI.create(url)); HttpResponse response = httpClient.execute(httpDelete); String httpEntityContent = getHttpEntityContent(response); httpDelete.abort(); return httpEntityContent; } /** * 封装HTTP DELETE方法 * * @param * @param * @return * @throws ClientProtocolException * @throws IOException */ public static String delete(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httpDelete.setConfig(requestConfig); List<NameValuePair> formparams = setHttpParams(paramMap); String param = URLEncodedUtils.format(formparams, "UTF-8"); httpDelete.setURI(URI.create(url + "?" + param)); HttpResponse response = httpClient.execute(httpDelete); String httpEntityContent = getHttpEntityContent(response); httpDelete.abort(); return httpEntityContent; } /** * 设置请求参数 * * @param * @return */ private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Set<Map.Entry<String, String>> set = paramMap.entrySet(); for (Map.Entry<String, String> entry : set) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return formparams; } /** * 获得响应HTTP实体内容 * * @param response * @return * @throws IOException * @throws UnsupportedEncodingException */ public static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = br.readLine(); StringBuilder sb = new StringBuilder(); while (line != null) { sb.append(line + "\n"); line = br.readLine(); } return sb.toString(); } return ""; } }
spring跨域请求数据:
/** * 跨域请求数据 * @param model * @param code * @return */ @RequestMapping(value = "/getDataFromCost") public void getDataFromCost(ModelAndView model,Long eprjInfoId,Long cprjInfoId,Integer uploadType,String loginname,String t,String h,String eprjAuthMap){ GenericIdentityBean identityBean = this.genGenericIdentity((IdentityBean)model.getModel().get(WebReviewParam.MODEL_IDENTITY)); UserObject user = userSessionService.getUser(identityBean); Map<String,String> postData = new HashMap<>(); //costHost = "http://localhost:8080/cost"; String url = costHost+"/token2"; if(user != null) { Map<String, Object> paramsObject; try { paramsObject = this.goToCost(model, 1l); postData.put("loginname", paramsObject.get("loginname")+""); postData.put("t", paramsObject.get("t")+""); postData.put("h", paramsObject.get("h")+""); postData.put("eprjInfoId", "0"); postData.put("uploadType", "50"); postData.put("cprjInfoId", cprjInfoId+""); postData.put("isChina", "false"); postData.put("remoteUrl", "down"); } catch (Exception e1) { e1.printStackTrace(); } String filename = "备份文件导出.hwp"; if(!UnitChange.isEmpty(loginname)){ try { filename = URLDecoder.decode(loginname, "utf-8"); } catch (Exception e) { } } try { HttpResponse postForResponse = HttpClientUtil.postForResponse(url, postData); HttpEntity entity = postForResponse.getEntity(); if(entity != null) { InputStream is = entity.getContent(); HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse(); String contentType = "application/x-hwp"; String contentDisposition="attachment;"; filename = URLEncoder.encode(filename, "UTF-8"); contentDisposition+="filename=\""+filename+"\""; response.setContentType(contentType); response.setHeader("accept-ranges", "bytes"); response.setHeader("Content-Disposition", contentDisposition); try { ServletOutputStream outputStream = response.getOutputStream(); IOUtils.copy(is, outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }
//获取跨域跳转需要的一些参数
/** * 跳转造价详细审核页面 * @return * @throws Exception */ @ResponseBody @RequestMapping(value = "/goToCost") public Map<String,Object> goToCost(ModelAndView model,Long eprjInfoId) throws Exception{ GenericIdentityBean identityBean = this.genGenericIdentity((IdentityBean)model.getModel().get(WebReviewParam.MODEL_IDENTITY)); UserObject user = userSessionService.getUser(identityBean); if(UnitChange.isEmpty(user.getSecretKey())) { user.setSecretKey(UuidUtil.uuid()); userService.update(identityBean, user.getId(), user); } Map<String,Object> returnMap = new HashMap<>(); returnMap.put("loginname", user.getUsername()); long t = new Date().getTime(); returnMap.put("t", t); String hash = MD5.encode16((user.getUsername()+user.getSecretKey()+t).getBytes(Charset.forName("UTF-8"))); returnMap.put("h", hash); returnMap.put("costHost", costHost); returnMap.put("costHost2", GlobalParameters.getServerUrl()+"/cost"); //跳转造价路径直接取当前域名+/cost returnMap.put("returnCode",EprjParam.SUCCESS); return returnMap; }
html页面和JS:
function downloadFile(url,paramObj){ var xhr = new XMLHttpRequest(); // xhr.open('GET', url, true); // 使用GET方式比较简单,参数直接附在URL上 xhr.open('POST', url, true); //POST的格式相对比较灵活,参数可以有比较多的形式,例如JSON,表单FORM等 xhr.responseType = "blob"; // 返回类型blob // xhr.setRequestHeader("Content-Type","application/json");//提交的数据为json格式 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //后台有使用JWT的token验证,会从请求头中读取"X-token"的值,所以这里在请求头加入"X-token" xhr.setRequestHeader("X-token", 'Bearer ' + localStorage.getItem(SAVE_AUTH)); // 定义请求完成的处理函数 xhr.onload = function () { jQuery.messager.progress('close'); // 请求完成 if (this.status === 200) { // 返回200 var blob = this.response; var reader = new FileReader(); reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href reader.onload = function (e) { // 转换完成,创建一个a标签用于下载 var a = document.createElement('a'); a.download = paramObj["cprjName"]+".hwp"; //可以通过导出空文件确认文件最小的长度为700000,如果长度过小,则表示远程抛出异常 if(e.target.result.indexOf("data:application/x-hwp") != -1 && e.target.result.length > 700000){ a.href = e.target.result; $("body").append(a); // 修复firefox中无法触发click a.click(); $(a).remove(); }else{ $.messager.show({ icon: "info", msg: "备份文件大小异常,可重新尝试备份操作!", position: "topCenter" ,timeout:1000, height:80}); } } }else{ $.messager.show({ icon: "info", msg: "备份文件大小异常,可重新尝试备份操作!", position: "topCenter" ,timeout:1000, height:80}); } }; // 发送ajax请求,案例中我们使用POST的请求格式,参数类型为JSON var param = {}; xhr.send(null); jQuery.messager.progress({ title:'请稍候...', text:'正在备份导出,请稍候...', interval:800 }); } function myDownFun(paramObj){ var url = "./iface/getDataFromCost?cprjInfoId="+paramObj["cprjInfoId"]; var rowData = $('#gcxh').treegrid('getSelected'); url += "&loginname="+encodeURIComponent(encodeURIComponent(rowData.name)); var postData = {}; postData["cprjName"] = rowData.cprjNameText; downloadFile(url,postData); // openPostWindow(url,data); } //本来可以使用form表单提交的方式,或者a连接的href进行导出,只是这两种方式不好捕捉和处理远程请求的异常exception //<a class="easyui-linkbutton" href="${object.publicResourcesUrl }" target="_blank" //title="备份导出" data-options="plain: true,iconCls:'fas fa-file-download e-icon fa-fw'" download>下载</a> function openPostWindow(url,obj) { var formStr = ''; //设置样式为隐藏,打开新标签再跳转页面前,如果有可现实的表单选项,用户会看到表单内容数据 formStr = '<form id="downTable" method="POST" action="' + url + '">'; formStr += '<input type="hidden" name="eprjInfoId" value="0" />'; formStr += '<input type="hidden" name="cprjInfoId" value="' + obj["cprjInfoId"] + '" />'; formStr += '<input type="hidden" name="uploadType" value="' + obj["uploadType"] + '" />'; formStr += '</form>'; $('body').append(formStr); $('#downTable')[0].submit(); $('#downTable').remove(); }
跨域访问的方法struts2
<action name="token2" method="token2" class="cost-importAndExportAction"> <result name="myJson" type="json"> <!-- 远程请求进度条信息,这里不用管 --> <param name="contentType">text/html</param> <param name="includeProperties">returnCode,message,data.*</param> <param name="ignoreHierarchy">false</param> <param name="enableGZIP" >true</param> </result> <result type="stroageStream"><!-- 远程请求文件流 --> <param name="contentDisposition">${contentDisposition}</param> <param name="contentType">${contentType}</param> <param name="inputName">inputStream</param> </result> <result name="login" type="redirect">/default</result> </action>
java(struts2):
public String token2(){ if(VerifyString.isEmpty(loginname) || eprjInfoId == null) { return "login"; } if (t<System.currentTimeMillis()/1000-60) { //1分钟内有效 return "login"; } UserObject userObject = null; try { userObject = userService.findByUsername(null, URLDecoder.decode(loginname, "utf-8")); } catch (Exception e) { } if (userObject==null) { throw new BaseException(this.getClass(),OrganException.USER_NOT_EXIST,""); } String hash =MD5.encode16((userObject.getUsername()+userObject.getSecretKey()+t).getBytes(Charset.forName("UTF-8"))); if (!hash.equalsIgnoreCase(h)) { throw new BaseException(this.getClass(),OrganException.USER_NOT_EXIST,""); } return this.download();//文件流 }
struts2的xml请求配置文件
<action name="download" method="download" class="cost-personnelsAction"> <result type="stroageStream"> <param name="contentDisposition">${contentDisposition}</param> <param name="contentType">${contentType}</param> <param name="inputName">inputStream</param> </result> </action>
文件流:
/** * 导出文件 * @return */ @Permission(authorize=Permission.AUTHORIZE_EXPORT) public String download() { Boolean isError=false; ActionContext context=ActionContext.getContext(); if (context==null) { return ActionSupport.ERROR; } Integer fileLength=0; HttpServletRequest request=(HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response=(HttpServletResponse)context.get(ServletActionContext.HTTP_RESPONSE);; try { String filename = ""; switch (this.uploadType) { case 50:// 建设项目 工程项目备份导出 { this.inputStream=cprjInfoService.backup(cprjInfoId, eprjInfoId); if(this.inputStream != null){ fileLength=this.inputStream.available(); int minLength=700000;//普通工程大小 //备份的建设项目或工程项目小于700000,代表备份文件有异常,报错 if(fileLength<minLength) { throw new Excpetion(this.getClass(), Cost.COST_ERROR, "备份文件大小异常"); } } } break; default: break; } if(inputStream != null) fileLength=inputStream.available(); else fileLength=0; String method=request.getMethod(); String userAgent=request.getHeader("User-Agent"); Browser browser=Browser.fromUserAgent(userAgent); this.contentType=FileContentType.buildContentType(filename); if("POST".equals(method)) { filename=URLEncoder.encode(filename, "UTF-8"); } else { switch(browser.getType()) { case Browser.IE: filename=URLEncoder.encode(filename, "UTF-8"); break; default: filename=new String(filename.getBytes(),"ISO8859-1"); break; } } this.contentDisposition="attachment;"; this.contentDisposition+="filename=\""+filename+"\""; response.setHeader("accept-ranges", "bytes"); // response.setHeader("content-length", String.valueOf(fileLength)); }catch(Exception e) { isError=true; if(e instanceof BaseException) { this.returnCode=((BaseException)e).getCode(); this.message=languageException.toString((BaseException)e); Log.error(e.getMessage(),e); } else { Log.error(e.getMessage(),e); this.returnCode=BaseException.UNKNOWN; this.message=languageException.toString(e); } response.setContentType("text/html;charset=UTF-8"); PrintWriter out; try { out = new PrintWriter(response.getWriter()); out.println("<html>"); out.println("<body bgcolor=\"white\">"); out.println("<span class=\"bold\">"+this.message+"</span>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e1) { } return ERROR; } finally { if(progress != null && userObject != null) { progress.put("progressValue", 102); progress.put("progressText", ""); userService.notsupSetProgressInfo(userObject, progress); } } if(!isError) return SUCCESS; else return ERROR;
到此,相信大家对“HttpClient远程请求struts2的文件流并实现下载的方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。