pom.xml引入
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
package com.util;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@SuppressWarnings("deprecation")
public class HttpUtil {
private static final Log log = LogFactory.getLog(HttpUtil.class);
/**
* post请求,通过键值对的形式,并非通过ResponseBody的形式
* @param connectionTimeout 连接超时时间,单位:毫秒
* @throws IOException
* @throws HttpException
*/
public static String doPost(String url, Map<String, String> map, int connectionTimeout) throws HttpException, IOException {
HttpClient httpClient = new HttpClient();
httpClient.setConnectionTimeout(connectionTimeout);
PostMethod postMethod = new PostMethod(url);
NameValuePair pair[] = new NameValuePair[map.size()];
int index = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
pair[index] = new NameValuePair(entry.getKey(), entry.getValue());
}
postMethod.addParameters(pair);
httpClient.executeMethod(postMethod);
String str = postMethod.getResponseBodyAsString();
log.info("返回消息:" + str);
return str;
}
/**
* post请求,通过ResponseBody的形式传参
* @param connectionTimeout 连接超时时间,单位:毫秒
* @throws IOException
* @throws HttpException
*/
public static String doPost(String url, String msg, int connectionTimeout) throws HttpException, IOException {
log.info("url=" + url);
log.info("msg=" + msg);
HttpClient httpClient = new HttpClient();
httpClient.setConnectionTimeout(connectionTimeout);
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestBody(msg);
postMethod.setRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(postMethod);
String str = postMethod.getResponseBodyAsString();
log.info("返回消息:" + str);
return str;
}
/**
* post请求,通过ResponseBody的形式传参
* @param header
* @param connectionTimeout 连接超时时间,单位:毫秒
* @throws IOException
* @throws HttpException
*/
public static String doPost(String url, String msg, List<Header> headerList, int connectionTimeout) throws HttpException, IOException {
log.info("url=" + url);
log.info("msg=" + msg);
HttpClient httpClient = new HttpClient();
httpClient.setConnectionTimeout(connectionTimeout);
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestBody(msg);
for (Header header : headerList) {
postMethod.setRequestHeader(header);
}
httpClient.executeMethod(postMethod);
String str = postMethod.getResponseBodyAsString();
log.info("返回消息:" + str);
return str;
}
}