package com.tenwa.httpclient; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.amarsoft.are.ARE; import com.tenwa.comm.exception.BusinessException; import com.tenwa.httpclient.resources.GPSConfigure; public class HttpClientUtil { public static String getData(String url, String methodType, Map params,boolean flag) throws Exception { long start = System.currentTimeMillis(); String result = ""; switch(methodType.toUpperCase()) { case "GET": result = loadDataGet(url, flag); break; case "POST": result = loadDataPost(url, params, flag); break; default: throw new RuntimeException("wrong method type"); } long end = System.currentTimeMillis(); ARE.getLog().info("response time : " + (end - start) + "ms"); return result; } /** * 通过POST的方式获取获得数据 * @param url * @param params * @return * @throws Exception */ private static String loadDataPost(String url,Map params, boolean flag) throws Exception { HttpClient httpClient = new HttpClient(); String result = ""; PostMethod postMethod = null; try { postMethod = new PostMethod(url); for(Entry param : params.entrySet()) { postMethod.addParameter(param.getKey(), param.getValue()); } if(flag) { postMethod.setRequestHeader("appkey", GPSConfigure.get("APPKEY")); } postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { InputStream txtis = postMethod.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(txtis, "UTF-8")); StringBuffer sbf = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sbf.append(line); } result = sbf.toString(); ARE.getLog().info(result); } else { throw new RuntimeException(statusCode + ""); } } catch(Exception e) { throw new RuntimeException(e); } finally { if(postMethod != null) postMethod.releaseConnection(); } return result; } /** * 通过GET的方式获取数据 * @param url * @param params * @return * @throws Exception */ private static String loadDataGet(String url, boolean flag) throws Exception { HttpClient httpClient = new HttpClient(); String result = ""; GetMethod postMethod = null; try { postMethod = new GetMethod(url); if(flag) { postMethod.setRequestHeader("appkey", GPSConfigure.get("APPKEY")); } postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { InputStream txtis = postMethod.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(txtis, "UTF-8")); StringBuffer sbf = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { sbf.append(line); } result = sbf.toString(); ARE.getLog().info(result); } else { throw new RuntimeException(statusCode + ""); } ARE.getLog().info(result); } catch(Exception e) { throw new RuntimeException(e); } finally { if(postMethod != null) postMethod.releaseConnection(); } return result; } /** * 通过使用CloseableHttpClient的 * @param url * @param params * @return */ private static String getDataPost(String url,Map params) { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(1000) .build(); CloseableHttpClient httpclient = null; CloseableHttpResponse result = null; String resultString = ""; try { httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); HttpPost postMethod = new HttpPost(url); /*postMethod .setHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");*/ postMethod.setHeader("Referer", url); List nvps = new ArrayList(); for(Entry param : params.entrySet()) { nvps.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 添加参数 postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); result = httpclient.execute(postMethod); HttpEntity repEntity = result.getEntity(); int statusCode = result.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return "410"; } resultString = EntityUtils.toString(repEntity, "UTF-8"); ARE.getLog().info(resultString); } catch (ConnectTimeoutException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { if (result != null) { try { result.close(); } catch (IOException e) { e.printStackTrace(); } } if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } return resultString; } public static String queryReport(String data, String type, String uploadPath) throws Exception { return queryReport(data, type, uploadPath, null); } public static String queryReport(String data, String type, String uploadPath, String applyId) throws Exception { Document doc = DocumentHelper.parseText(data); Element root = doc.getRootElement(); Element returnValue = root.element("returnValue"); byte[] byteData = new Base64().decode(returnValue.getText()); String filePath = "";//获取html页面的存储路径,并展示给用户 if("html".equals(type)) { //输出文件 filePath = writeByteData(byteData, uploadPath, applyId); //解压文件 String htmlFileName = unzipFile(filePath); //找到html页面 filePath = new File(new File(new File(htmlFileName).getParent()).getParent()).getName() + "@" + htmlFileName; } else if("pdf".equals(type)) { filePath = writeByteData(byteData, uploadPath); } else { filePath = writeByteData(byteData, uploadPath); } return filePath; } //递归解压缩文件 public static String unzipFile(String filePath) throws Exception { if(filePath == null || !filePath.endsWith(".zip")) { throw new BusinessException("not a zipfile"); } ZipInputStream zip = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; String htmlFilePath = ""; String zipPath = filePath; try { zip = new ZipInputStream(new FileInputStream(filePath)); filePath = filePath.substring(0, filePath.indexOf("html") + 4); bis = new BufferedInputStream(zip); ZipEntry zipEntry = null; while((zipEntry = zip.getNextEntry()) != null) { String fileName = zipEntry.getName(); fileName = filePath + "/" + fileName; if(fileName.endsWith(".zip")) {//是压缩文件就继续解压 unzipFile(fileName); } else { File file = new File(fileName); if(!file.exists()) { new File(file.getParent()).mkdirs();//文件不存在,则先创建目录群 } if(fileName.endsWith(".html")) { htmlFilePath = fileName; } bos = new BufferedOutputStream(new FileOutputStream(file)); int n = -1; while((n = bis.read()) != -1) { bos.write(n); } bos.flush(); } } } catch(Exception e) { e.printStackTrace(); throw new BusinessException("文件解压失败"); } finally { if(zip != null) zip.close(); if(fos != null) fos.close(); if(bis != null) bis.close(); if(bos != null) bos.close(); new File(zipPath).delete(); } return htmlFilePath; } public static String writeByteData(byte[] byteData, String uploadPath) throws Exception { return writeByteData(byteData, uploadPath, null); } public static String writeByteData(byte[] byteData, String uploadPath, String applyId) throws Exception { String filePath = ""; ByteArrayInputStream bis = null; FileOutputStream fos = null; ZipInputStream zip = null; File file = null; try { bis = new ByteArrayInputStream(byteData); //首输出压缩文件 zip = new ZipInputStream(bis);//读取zip流 ZipEntry zipEntry = zip.getNextEntry(); //filePath = uploadPath + zipEntry.getName(); //为了避免并发导致读取文件冲突,为文件名加上时间戳 String code = System.currentTimeMillis() + ""; //增加applyId为存储名,确保并发情况下低概率出现时间戳一致的情况 if(applyId != null && !"".equals(applyId)) { code = applyId; } filePath = uploadPath + zipEntry.getName().replaceAll(".zip", "/"+code + ".zip"); file = new File(filePath); if(!file.exists()) { new File(file.getParent()).mkdirs(); } fos = new FileOutputStream(file); if(zipEntry != null) { byte[] buf = new byte[1024]; int n = -1; while((n = zip.read(buf, 0, buf.length)) != -1) { fos.write(buf, 0, n); } fos.flush(); } } catch(Exception e) { e.printStackTrace(); throw new BusinessException("读写文件失败"); } finally { if(bis != null) bis.close(); if(fos != null) fos.close(); } return filePath; } public static String getQueryCondition(Map params) { try { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("conditions"); Element condition = root.addElement("condition"); condition.addAttribute("queryType",params.get("queryType")); for(Entry param : params.entrySet()) { if("queryType".equals(param.getKey())) { continue; } Element item = condition.addElement("item"); item.addElement("name").setText(param.getKey()); item.addElement("value").setText(param.getValue()); } return doc.asXML(); } catch (Exception e) { e.printStackTrace(); } return null; } }