十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本篇内容主要讲解“HttpClient远程请求struts2的文件流并实现下载的方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“HttpClient远程请求struts2的文件流并实现下载的方法”吧!
我们提供的服务有:网站设计、做网站、微信公众号开发、网站优化、网站认证、寿阳ssl等。为成百上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的寿阳网站制作公司
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, MapparamMap) 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 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 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 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 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 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 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 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 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 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 setHttpParams(Map paramMap) { List formparams = new ArrayList (); Set > set = paramMap.entrySet(); for (Map.Entry 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); MappostData = new HashMap<>(); //costHost = "http://localhost:8080/cost"; String url = costHost+"/token2"; if(user != null) { Map 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 MapgoToCost(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 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 //下载 function openPostWindow(url,obj) { var formStr = ''; //设置样式为隐藏,打开新标签再跳转页面前,如果有可现实的表单选项,用户会看到表单内容数据 formStr = ''; $('body').append(formStr); $('#downTable')[0].submit(); $('#downTable').remove(); }
跨域访问的方法struts2
text/html returnCode,message,data.* false true ${contentDisposition} ${contentType} inputStream /default
java(struts2):
public String token2(){ if(VerifyString.isEmpty(loginname) || eprjInfoId == null) { return "login"; } if (tstruts2的xml请求配置文件
${contentDisposition} ${contentType} inputStream 文件流:
/** * 导出文件 * @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"); out.println(""); out.println(""+this.message+""); out.println(""); out.println("