需要添加相应的jar包
package com.http_request.httpclient;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* @author xiaoli
* HttpClient
*/
public class GetHttpClient {
/**
* 默认的编码,解决中文乱码
*/
public static String defaultEncode = "UTF-8";
/**
* 发送Get请求
* @param url 请求路径
* @param paramMap 参数
* @return 响应体
*/
public static String getSendGet(String url,Map<String, String> paramMap){
return getSendGet(url, paramMap, defaultEncode);
}
/**
* 发送Get请求
* @param url 请求路径
* @param paramMap 参数
* @param encode 编码
* @return 响应体
*/
public static String getSendGet(String url,Map<String, String> paramMap,String encode){
StringBuffer buf = new StringBuffer();
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
if(paramMap.size()>0){
NameValuePair[] params = new NameValuePair[paramMap.size()];
Iterator<Entry<String, String>> it = paramMap.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry<String, String> map = (Map.Entry<String, String>) it.next();
params[i] = new NameValuePair(map.getKey(),map.getValue());
i++;
}
getMethod.setQueryString(params); // post请求参数用setQueryString
}
try {
client.executeMethod(getMethod);
byte[] responseBody = getMethod.getResponseBody();
String content = new String(responseBody,encode);
buf.append(content);
}catch (Exception e) {
e.printStackTrace();
}finally{
getMethod.releaseConnection();
}
return buf.toString();
}
/**
* 发送Post请求
* @param url 请求路径
* @param paramMap 参数
* @return 响应体
*/
public static String getSendPost(String url,Map<String, String> paramMap){
return getSendPost(url, paramMap, defaultEncode);
}
/**
* 发送Post请求
* @param url 请求路径
* @param paramMap 参数
* @return 响应体
*/
public static String getSendPost(String url,Map<String, String> paramMap,String encode){
StringBuffer buf = new StringBuffer();
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset="+encode);
if(paramMap.size()>0){
NameValuePair[] params = new NameValuePair[paramMap.size()];
Iterator<Entry<String, String>> it = paramMap.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry<String, String> map = (Map.Entry<String, String>) it.next();
params[i] = new NameValuePair(map.getKey(),map.getValue());
i++;
}
postMethod.setRequestBody(params); // post请求参数用setRequestBody
}
try {
client.executeMethod(postMethod);
byte[] responseBody = postMethod.getResponseBody();
String content = new String(responseBody,encode);
buf.append(content);
}catch (Exception e) {
e.printStackTrace();
}finally{
postMethod.releaseConnection();
}
return buf.toString();
}
}