上线前的压测问题:
第一版的httpClient请求工具类:
1.由于把地址写成全局变量,每次调用其他系统的接口时:
httpClient.setAddress("136.224.224.36"),httpClient.post();
这种方式导致上一次的请求地址没有被变更,然后请求参数和请求地址不匹配,导致混乱。第三方的系统接收到的参数不正确。
2.当压测进行接口压测的时候,2、3分钟就报了(address already in used)连接数被占满的异常。这是由于没有在请求头中设置关闭连接,如果对面的返回时间较长。会导致连接不释放。method.setRequestHeader("Connection","close");
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
/**
* @ClassName HttpClientUtils
* @Description http 客户端请求工具类
* modify by fee 20151229
* 增加调用日志记录
* @author t-liuyong
* @date 2015-3-15
*/
@Component
public class HttpClientUtils {
private static final Logger log = Logger.getLogger(HttpClientUtils.class);
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final int TIME_OUT = 60000; // 60秒
private String address;
private Boolean devFlag;
// 指定编码格式
private static final String CODING_FORMAT = "text/html;charset=UTF-8";// "application/x-www-form-urlencoded;charset=UTF-8";
// 指定编码格式
private static final String CODING_FORMAT_CMS = "application/json;charset=UTF-8";
/***
* post请求模拟
* @param requestBody
* @param headerMap
* @return
* @throws Exception
*/
public String postInvoker(String requestBody, Map<String, String> headerMap) throws Exception {
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
Boolean success = false;
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
/*if (devFlag) {
client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
8080);
}*/
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
// return new String(method.getResponseBody(), "utf-8");
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
success = true;
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
/*
*发送不带参数的post请求
* @param String url
*/
public static String SendPost(String url){
String result = null;
//得到一个HTTP对象
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
//执行一个httpPost请求,并得到一个CloseableHttpResponse
response = httpclient.execute(httpPost);
//从CloseableHttpResponse中拿到httpEntity
HttpEntity entity = response.getEntity();
//将HttpEntry转换成字符串
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭CloseableHttpResponse
if (response != null){
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
}
return result;
}
/***
* post请求模拟(只为上海银行卡支付流程)
* @param requestBody
* @param headerMap
* @return
* @throws Exception
*/
public String specialPostInvoker(String requestBody, Map<String, String> headerMap) throws Exception {
HttpConnectionManager httpConnectionManager=new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(
httpConnectionManager);
HttpConnectionManagerParams httpConnectionManagerParams=httpConnectionManager.getParams();
httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(16);
httpConnectionManagerParams.setMaxTotalConnections(128);
Boolean success = false;
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
InputStream responseStream= null;
BufferedReader br =null;
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
// return new String(method.getResponseBody(), "utf-8");
responseStream = method.getResponseBodyAsStream();
br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
success = true;
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
public String postInvokerCms(String requestBody, Map<String, String> headerMap) throws Exception {
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT_CMS);
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT_CMS, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
public String requestXML(String requestXML, String strURL) throws Exception {
StringBuilder buffer = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
String strMessage = "";
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
managerParams.setConnectionTimeout(10000);
managerParams.setSoTimeout(120000);
PostMethod postMethod = new PostMethod(strURL);
try {
postMethod.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "GBK"));
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
}
inputStream = postMethod.getResponseBodyAsStream();
reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
while ((strMessage = reader.readLine()) != null) {
buffer.append(strMessage);
}
} catch (Exception ex) {
throw new IllegalStateException(ex.toString());
} finally {
if(reader!=null){
reader.close();
}
if(inputStream!=null){
inputStream.close();
}
postMethod.releaseConnection();
}
return buffer.toString();
}
/**
* get请求模拟
* @param headerMap
* @return
* @throws Exception
*/
public String getInvoker(Map<String, String> headerMap) throws Exception {
Boolean success = false;
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
GetMethod method = new GetMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
// if (devFlag) {
// client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
// 8080);
// }
try {
// RequestEntity requestEntity = new
// StringRequestEntity(requestBody, CODING_FORMAT,"UTF-8");
// method.setRequestEntity(requestEntity);
client.executeMethod(method);
byte[] bytes = method.getResponseBody();
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + " "
+ e.getMessage());
} finally {
method.releaseConnection();
}
}
public String getUrlBind(String address) throws Exception{
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
log.info("调人寿接口查询预绑定信息异常:"+e);
}
return result;
}
/**
* get请求模拟
* @param headerMap
* @return
* @throws Exception
*/
public byte[] getInvokerStream(Map<String, String> headerMap) throws Exception {
Boolean success = false;
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
GetMethod method = new GetMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
if (devFlag) {
client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
8080);
}
try {
// RequestEntity requestEntity = new
// StringRequestEntity(requestBody, CODING_FORMAT,"UTF-8");
// method.setRequestEntity(requestEntity);
client.executeMethod(method);
byte[] bytes = method.getResponseBody();
return bytes;
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + " "
+ e.getMessage());
} finally {
method.releaseConnection();
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Boolean getDevFlag() {
return devFlag;
}
public void setDevFlag(Boolean devFlag) {
this.devFlag = devFlag;
}
}
因此对第一版进行了修改:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
/**
* @ClassName HttpClientUtils
* @Description http 客户端请求工具类
* modify by fee 20151229
* 增加调用日志记录
* @author t-liuyong
* @date 2015-3-15
*/
@Component
public class HttpClientUtils {
private static final Logger log = Logger.getLogger(HttpClientUtils.class);
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final int TIME_OUT = 60000; // 60秒
private Boolean devFlag;
// 指定编码格式
private static final String CODING_FORMAT = "text/html;charset=UTF-8";// "application/x-www-form-urlencoded;charset=UTF-8";
// 指定编码格式
private static final String CODING_FORMAT_CMS = "application/json;charset=UTF-8";
/***
* post请求模拟
* @param requestBody
* @param headerMap
* @return
* @throws Exception
*/
public String postInvoker(String address,String requestBody, Map<String, String> headerMap) throws Exception {
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
Boolean success = false;
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
/*if (devFlag) {
client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
8080);
}*/
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
// return new String(method.getResponseBody(), "utf-8");
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
success = true;
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
/*
*发送不带参数的post请求
* @param String url
*/
public static String SendPost(String url){
String result = null;
//得到一个HTTP对象
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
//执行一个httpPost请求,并得到一个CloseableHttpResponse
response = httpclient.execute(httpPost);
//从CloseableHttpResponse中拿到httpEntity
HttpEntity entity = response.getEntity();
//将HttpEntry转换成字符串
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭CloseableHttpResponse
if (response != null){
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
}
return result;
}
/***
* post请求模拟(只为上海银行卡支付流程)
* @param requestBody
* @param headerMap
* @return
* @throws Exception
*/
public String specialPostInvoker(String address,String requestBody, Map<String, String> headerMap) throws Exception {
HttpConnectionManager httpConnectionManager=new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(
httpConnectionManager);
HttpConnectionManagerParams httpConnectionManagerParams=httpConnectionManager.getParams();
httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(16);
httpConnectionManagerParams.setMaxTotalConnections(128);
Boolean success = false;
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
InputStream responseStream= null;
BufferedReader br =null;
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
// return new String(method.getResponseBody(), "utf-8");
responseStream = method.getResponseBodyAsStream();
br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
success = true;
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
public String postInvokerCms(String address,String requestBody, Map<String, String> headerMap) throws Exception {
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
PostMethod method = new PostMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT_CMS);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
try {
RequestEntity requestEntity = new StringRequestEntity(requestBody,
CODING_FORMAT_CMS, "UTF-8");
method.setRequestEntity(requestEntity);
client.executeMethod(method);
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + "*****body*****" + requestBody
+ "*****," + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + "*****body*****"
+ requestBody + "*****," + e.getMessage());
} finally {
method.releaseConnection();
}
}
public String requestXML(String requestXML, String strURL) throws Exception {
StringBuilder buffer = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
String strMessage = "";
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
managerParams.setConnectionTimeout(10000);
managerParams.setSoTimeout(120000);
PostMethod postMethod = new PostMethod(strURL);
try {
postMethod.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "GBK"));
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new IllegalStateException("Method failed: " + postMethod.getStatusLine());
}
inputStream = postMethod.getResponseBodyAsStream();
reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
while ((strMessage = reader.readLine()) != null) {
buffer.append(strMessage);
}
} catch (Exception ex) {
throw new IllegalStateException(ex.toString());
} finally {
if(reader!=null){
reader.close();
}
if(inputStream!=null){
inputStream.close();
}
postMethod.releaseConnection();
}
return buffer.toString();
}
/**
* get请求模拟
* @param headerMap
* @return
* @throws Exception
*/
public String getInvoker(String address,Map<String, String> headerMap) throws Exception {
Boolean success = false;
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
GetMethod method = new GetMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
// if (devFlag) {
// client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
// 8080);
// }
try {
// RequestEntity requestEntity = new
// StringRequestEntity(requestBody, CODING_FORMAT,"UTF-8");
// method.setRequestEntity(requestEntity);
client.executeMethod(method);
byte[] bytes = method.getResponseBody();
InputStream responseStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
responseStream));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + " "
+ e.getMessage());
} finally {
method.releaseConnection();
}
}
public String getUrlBind(String address) throws Exception{
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
log.info("调人寿接口查询预绑定信息异常:"+e);
}
return result;
}
/**
* get请求模拟
* @param headerMap
* @return
* @throws Exception
*/
public byte[] getInvokerStream(String address,Map<String, String> headerMap) throws Exception {
Boolean success = false;
HttpClient client = new HttpClient(
new MultiThreadedHttpConnectionManager());
GetMethod method = new GetMethod(address);
// 超时机制
HttpMethodParams methodParams = new HttpMethodParams();
methodParams.setSoTimeout(TIME_OUT);
method.setParams(methodParams);
method.addRequestHeader("Content-Type", CODING_FORMAT);
method.setRequestHeader("Connection","close");
if(headerMap!=null&&headerMap.size()>0){
Iterator<Entry<String, String>> it = headerMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// !!!!!!!!!!!!!!!!!!!!设置代理,正式环境需要去掉!!!!!!!!!!!!!!!!!!!!
if (devFlag) {
client.getHostConfiguration().setProxy("proxy6.taikanglife.com",
8080);
}
try {
// RequestEntity requestEntity = new
// StringRequestEntity(requestBody, CODING_FORMAT,"UTF-8");
// method.setRequestEntity(requestEntity);
client.executeMethod(method);
byte[] bytes = method.getResponseBody();
return bytes;
} catch (HttpException e) {
log.error("无法连接到指定地址url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("无法连接到指定地址url:" + address + " "
+ e.getMessage());
} catch (Exception e) {
log.error("请求失败url:" + address + " " + e.getMessage());
e.printStackTrace();
throw new Exception("请求失败url:" + address + " "
+ e.getMessage());
} finally {
method.releaseConnection();
}
}
public Boolean getDevFlag() {
return devFlag;
}
public void setDevFlag(Boolean devFlag) {
this.devFlag = devFlag;
}
}
在上线前的压测中,原始的HttpClient工具类暴露了两个问题:一是全局变量地址导致请求混乱,使得第三方系统接收错误参数;二是未设置关闭连接,造成连接数占满异常。解决方案是针对每次请求更改地址,并在请求头中设置“Connection”为“close”,以确保连接释放。

被折叠的 条评论
为什么被折叠?



