apzl_leasing/src_cmb/com/tenwa/cgb/util/HttpAssistant.java
2021-07-29 10:27:26 +08:00

65 lines
2.3 KiB
Java

package com.tenwa.cgb.util;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @program: apzl_leasing
* @author: yjf
* @create: 2021-07-20 08:43
**/
public class HttpAssistant {
private static Log log = LogFactory.getLog(HttpAssistant.class);
private static final HttpClient httpClient = new HttpClient();
static {
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
}
public static String post(String reqUrl, Map<String, Object> paramMap) {
String result = null;
PostMethod postMethod = null;
try {
postMethod = new PostMethod(reqUrl);
// 这个basicNameValue**放在List中
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// 创建basicNameValue***对象参数
if (paramMap != null) {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
nameValuePairs.add(new NameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
// 填入各个表单域的值
NameValuePair[] param = nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]);
postMethod.addParameters(param);
postMethod.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=gbk");
postMethod.setRequestHeader("Cache-Control", "no-cache");
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
result = postMethod.getResponseBodyAsString();
}
} catch (IOException e) {
log.error("执行HTTP Post请求" + reqUrl + "时,发生异常:", e);
} finally {
if (postMethod != null) postMethod.releaseConnection();
}
return result;
}
}