个人理解,这个方法就是解析url,分解成ip 和 端口号,为了后面httpclient连接做准备
EntityEnclosingMethod httpMethod = new PostMethod(url);
EntityEnclosingMethod--实体封闭方法
// 跟踪一下方法 1
public PostMethod(String uri) {
super(uri);
}
// 跟踪一下方法 next
public EntityEnclosingMethod(String uri) {
super(uri);
setFollowRedirects(false);
}
//期待继续方法
public ExpectContinueMethod(String uri) {
super(uri);
}
// 跟踪一下方法 next
public HttpMethodBase(String uri)
throws IllegalArgumentException, IllegalStateException {
try {
// create a URI and allow for null/empty uri values
if (uri == null || uri.equals("")) {
uri = "/";
}
String charset = getParams().getUriCharset();
setURI(new URI(uri, true, charset));
} catch (URIException e) {
throw new IllegalArgumentException("Invalid uri '"
+ uri + "': " + e.getMessage()
);
}
}
// 跟踪一下方法 next
public void setURI(URI uri) throws URIException {
// only set the host if specified by the URI
if (uri.isAbsoluteURI()) {
this.httphost = new HttpHost(uri);
}
// set the path, defaulting to root
setPath(
uri.getPath() == null
? "/"
: uri.getEscapedPath()
);
setQueryString(uri.getEscapedQuery());
}
设置header信息
// 设置header信息,传输json格式的
httpMethod.setRequestHeader("accept", "application/json");
httpMethod.setRequestHeader("content-type", "application/json; charset=UTF-8");
// 设置header信息,传输XML格式的
httpMethod.setRequestHeader("content-type", "text/xml; charset=UTF-8");
// 发送含消息体的对象
// 发送含xml消息体的对象
RequestEntity entity = new StringRequestEntity(String xml,"text/xml", "UTF-8");
// 发送含json消息体的对象
RequestEntity entity = new StringRequestEntity(String json, "application/json", "UTF-8");
// 绑定实体关系
httpMethod.setRequestEntity(entity);
// 处理响应结果码
resultCode = getHttpClient().executeMethod(httpMethod);
getHttpClient()方法
private static HttpClient getHttpClient() {
// 使用连接池技术创建HttpClient对象
HttpClient httpClient = new HttpClient(connectionManager);
return httpClient;
}
private static MultiThreadedHttpConnectionManager connectionManager;
/**
* HttpUtil初始化块
*/
static {
connectionManager = new MultiThreadedHttpConnectionManager();
maxTotalConnectNum = MAX_TOTAL_CONNECTIONS;
maxConnectPerHost = MAX_CONNECTIONS_PER_HOST;
connTimeout = CONNECTION_TIMEOUT;
socketTimeout = SOCKET_TIMEOUT;
retryCount = MAX_RETRY_COUNT;
// 设定参数:客户端的总连接数
connectionManager.getParams()
.setMaxTotalConnections(maxTotalConnectNum);
// 设定参数:与每个主机的最大连接数
connectionManager.getParams().setDefaultMaxConnectionsPerHost(
maxConnectPerHost);
// 设置超时时间
connectionManager.getParams().setConnectionTimeout(connTimeout);
connectionManager.getParams().setSoTimeout(socketTimeout);
}
post - xml 格式请求
public static String sendHttpRequestHeaderXML(String url, String xml ,Map<String ,String> headers) {
log.info("Enter sendHttpRequest()!=>" + "url=" + url);
log.info("发送报文:" + xml);
EntityEnclosingMethod httpMethod = new PostMethod(url);
int resultCode = 0;
String responseXML = null;
try {
// 设置header信息,传输XML格式的
httpMethod.setRequestHeader(CONT_TYPE, CONT_TYPE_VAL_XML_UTF8);
if (headers != null && headers.size() >= 1){
for (String key : headers.keySet()){
if (StringUtil.isEmpty(key) || StringUtil.isEmpty(headers.get(key))){
log.info("Enter sendHttpRequest()!=>" + "设置消header不能为null=" + headers.toString());
return null;
}
log.info("Enter sendHttpRequest()!=>" + "设置消header成功,key=" +key +",value="+headers.get(key) );
httpMethod.setRequestHeader(key,headers.get(key));
}
}
// 发送含xml消息体的对象
RequestEntity entity = new StringRequestEntity(xml,
CONT_TYPE_TEXT_XML, CHARSET_UTF8);
// 绑定实体关系
httpMethod.setRequestEntity(entity);
// 处理响应结果码
resultCode = getHttpClient().executeMethod(httpMethod);
if (resultCode != HttpStatus.SC_OK) {
log.error("send http request error,ResponseCode=" + resultCode
+ ",url=" + url);
}
byte[] resBody = httpMethod.getResponseBody();
if (null == resBody || resBody.length == 0) {
responseXML = httpMethod.getResponseBodyAsString();
} else {
responseXML = new String(resBody, CHARSET_UTF8);
}
if (log.isInfoEnabled()) {
log.info("Exit sendHttpRequest()!=>" + "response xml="
+ responseXML);
}
} catch (Exception e) {
if (url.contains("nss")) {
// TODO后续添加nss任务失败处理
}
log.error("send http request error!", e);
} finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
return responseXML;
}
post - json 格式请求
/**
* 通过http发送json到cps,并返回应答
*
* @param url
* @param json
* @return
*/
public String sendJsonRequestToCPS(String url, String json) {
logger.info("Enter sendJsonRequest()!" + " url: " + url + " ,json: " + json);
EntityEnclosingMethod httpMethod = new PostMethod(url);
int resultCode = 0;
String responseJson = null;
try {
// 设置header信息
httpMethod.setRequestHeader(ACCEPT, ACCEPT_VALUE);
httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_JSON_UTF_8);
// 发送消息体的对象
// 发送含json消息体的对象
RequestEntity entity = null;
entity = new StringRequestEntity(json, APPLICATION_JSON, "UTF-8");
// 绑定实体关系
httpMethod.setRequestEntity(entity);
// 处理响应结果码
resultCode = httpClient.executeMethod(httpMethod);
if (resultCode != HttpStatus.SC_OK) {
String[][] appInfo = {{"resultCode", String.valueOf(resultCode)}, {"url", url}};
logger.error("The response code is error!", appInfo);
}
// 获取响应报文
httpMethod.getResponseBodyAsStream();
byte[] resBody = httpMethod.getResponseBody();
if (null == resBody || resBody.length == 0) {
responseJson = httpMethod.getResponseBodyAsString();
} else {
responseJson = new String(resBody, "UTF-8");
}
logger.info("Exit sendJsonRequest()!" + " url: " + url + " ,response json: " + responseJson);
} catch (Exception e) {
logger.error("send http request error!", e);
} finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
return responseJson;
}