apzl_leasing/src_tenwa/com/tenwa/httpclient/HttpClientUtil.java
2019-06-10 17:34:32 +08:00

356 lines
11 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<String, String> 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;
}
/**
* ͨ<><CDA8>POST<53>ķ<EFBFBD>ʽ<EFBFBD><CABD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
* @param url
* @param params
* @return
* @throws Exception
*/
private static String loadDataPost(String url,Map<String, String> params, boolean flag) throws Exception {
HttpClient httpClient = new HttpClient();
String result = "";
PostMethod postMethod = null;
try {
postMethod = new PostMethod(url);
for(Entry<String, String> 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;
}
/**
* ͨ<><CDA8>GET<45>ķ<EFBFBD>ʽ<EFBFBD><CABD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>
* @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;
}
/**
* ͨ<><CDA8>ʹ<EFBFBD><CAB9>CloseableHttpClient<6E><74>
* @param url
* @param params
* @return
*/
private static String getDataPost(String url,Map<String, String> 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<NameValuePair> nvps = new ArrayList<NameValuePair>();
for(Entry<String, String> param : params.entrySet()) {
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// <20><><EFBFBD>Ӳ<EFBFBD><D3B2><EFBFBD>
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 = "";//<2F><>ȡhtmlҳ<6C><D2B3><EFBFBD>Ĵ洢·<E6B4A2><C2B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>չʾ<D5B9><CABE><EFBFBD>û<EFBFBD>
if("html".equals(type)) {
//<2F><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
filePath = writeByteData(byteData, uploadPath, applyId);
//<2F><>ѹ<EFBFBD>ļ<EFBFBD>
String htmlFileName = unzipFile(filePath);
//<2F>ҵ<EFBFBD>htmlҳ<6C><D2B3>
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;
}
//<2F>ݹ<EFBFBD><DDB9><EFBFBD>ѹ<EFBFBD><D1B9><EFBFBD>ļ<EFBFBD>
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")) {//<2F><>ѹ<EFBFBD><D1B9><EFBFBD>ļ<EFBFBD><C4BC>ͼ<EFBFBD><CDBC><EFBFBD><EFBFBD><EFBFBD>ѹ
unzipFile(fileName);
} else {
File file = new File(fileName);
if(!file.exists()) {
new File(file.getParent()).mkdirs();//<2F>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD><EFBFBD>ȴ<EFBFBD><C8B4><EFBFBD>Ŀ¼Ⱥ
}
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("<EFBFBD>ļ<EFBFBD><EFBFBD><EFBFBD>ѹʧ<EFBFBD><EFBFBD>");
} 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);
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѹ<EFBFBD><D1B9><EFBFBD>ļ<EFBFBD>
zip = new ZipInputStream(bis);//<2F><>ȡzip<69><70>
ZipEntry zipEntry = zip.getNextEntry();
//filePath = uploadPath + zipEntry.getName();
//Ϊ<>˱<EFBFBD><CBB1><EFBFBD><E2B2A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD>ļ<EFBFBD><C4BC><EFBFBD>ͻ,Ϊ<>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>
String code = System.currentTimeMillis() + "";
//<2F><><EFBFBD><EFBFBD>applyIdΪ<64><EFBFBD><E6B4A2><EFBFBD><EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>µ͸<C2B5><CDB8>ʳ<EFBFBD><CAB3><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>һ<EFBFBD>µ<EFBFBD><C2B5><EFBFBD><EFBFBD><EFBFBD>
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("<EFBFBD><EFBFBD>д<EFBFBD>ļ<EFBFBD>ʧ<EFBFBD><EFBFBD>");
} finally {
if(bis != null) bis.close();
if(fos != null) fos.close();
}
return filePath;
}
public static String getQueryCondition(Map<String,String> params) {
try {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("conditions");
Element condition = root.addElement("condition");
condition.addAttribute("queryType",params.get("queryType"));
for(Entry<String, String> 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;
}
}