HttpClient工具

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * HttpClient请求工具
 */
public class HttpClientUtil {
private static  Log log   = LogFactory.getLog(HttpClientUtil.class);
private static final int TIMEOUT =  180000;
private static final String POST = "post";
private static final String GET = "get";
public static final String UTF8_CHARSET = "UTF-8";
public static final String GBK_CHARSET = "GBK";
/**
* 向指定URL发送GET方法的请求
* @param url   发送请求的 URL
* @param param 请求参数
* @return      所代表远程资源的响应结果
*/
public static String sendGet(String url, Map<String,String> param,String charset) {
GetMethod  method = new GetMethod(url);
if(param == null){
param = new HashMap<String,String>();
}
return execute(method,url,param,charset,GET);
}

/**
* 向指定 URL 发送POST方法的请求
* @param url   发送请求的 URL
* @param param 请求参数
* @return      所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String,String> param,String charset) {
PostMethod  method = new PostMethod(url);
if(param == null){
param = new HashMap<String,String>();
}
return execute(method,url,param,charset,POST);
}

/**
* 执行HttpClient请求
* @return
*/
private static String execute(HttpMethodBase method,String url,Map<String,String> param,String charset,String type){
try {
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset(charset);
httpClient.getParams().setConnectionManagerTimeout(TIMEOUT);
method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, TIMEOUT);
method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset="+charset);
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);

//请求信息封装
NameValuePair[] data = new NameValuePair[param.size()]; 
Iterator<Entry<String, String>> iter = param.entrySet().iterator();
int i=0;
while(iter.hasNext()){
Entry<String, String> entry = iter.next();
data[i] = new NameValuePair(entry.getKey(), entry.getValue()); 
i++;
}
if(type.equals(GET)){
method.setQueryString(data);
}else{
PostMethod postMethod = (PostMethod)method;
postMethod.setRequestBody(data);
}
httpClient.executeMethod(method);
String submitResult = IOUtils.toString(method.getResponseBodyAsStream(), charset);
return submitResult;
} catch (Exception e) {
log.error(getRequestParam(url,param), e);
}
return null;
}

/**
* 拼装请求参数信息
*/
private static String getRequestParam(String url, Map<String,String> param){
Iterator<Entry<String, String>> iter = param.entrySet().iterator();
StringBuffer sb = new StringBuffer();
sb.append("HTTPClient请求URL地址:").append(url).append(",请求参数:");
sb.append("[");
while(iter.hasNext()){
Entry<String, String> entry = iter.next();
sb.append(entry.getKey()).append("=").append(entry.getValue());
if(iter.hasNext()){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和处理响应。它是 Apache HttpComponents 项目的一部分,提供了简单且灵活的 API,用于进行 HTTP 通信。 你可以使用 HttpClient 来执行各种 HTTP 操作,如发送 GET、POST、PUT、DELETE 等请求。它支持处理响应、处理重定向、处理认证、处理代理等功能。 以下是使用 HttpClient 发送 GET 请求的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet("http://example.com"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity); System.out.println(responseString); } } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码使用 HttpClient 发送了一个 GET 请求,并打印了响应内容。你可以根据需要修改代码以适应其他类型的请求和操作。 请注意,HttpClient 的最新版本是 HttpClient 5.x,但上述示例使用的是 HttpClient 4.x 的 API。你可以根据自己的需求选择使用哪个版本。 希望这个回答能对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值