Java使用HttpClient进行Http相关操作

HttpClient可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。在本文中给出了HttpClient基础使用的说明。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
* 本类为HTTP请求相关工具类,在该类中可以处理通用的HTTP各种请求
*
* @author yuanyao
*
*/
@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
public class HttpUtil {

private String url = null;
private HttpClient httpClient = null;
private HttpRequestBase request = null;
private HttpResponse response = null;

/**
* HTTP请求类型
*
* @author yuanyao
*
*/
public enum HttpType {
GET("Get"), POST("Post"), HEAD("Head"), PUT("Put"), DELETE("Delete"), OPTIONS(
"Options"), TRACE("Trace"), PATCH("Patch");
private String key;

private HttpType(String key) {
this.key = key;
}

public String getKey() {
return key;
}
}

public HttpUtil(String url) {
this.url = url;
}

/**
* 获取HTTP请求响应内容
*
* @param url
* 请求URL地址
* @param type
* HTTP请求类型
* @param postParams
* 当请求为POST时提供的POST参数
* @return HTTP响应返回内容
* @throws Exception
*/
public String getHttpResponseContent(HttpType type,
Map<String, String> postParams) throws Exception {
HttpEntity entity = getHttpResponseEntity(type, postParams);
String content = "";
if (entity != null) {
InputStream instreams = entity.getContent();
content = convertStreamToString(instreams);
}
close();
return content;
}

/**
* 返回HTTP响应结果实体
*
* @param url
* 请求URL地址
* @param type
* HTTP请求类型
* @param postParams
* 当请求为POST时提供的POST参数
* @return HTTP响应实体
* @throws Exception
*/
private HttpEntity getHttpResponseEntity(HttpType type,
Map<String, String> postParams) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpRequestBase request = getMethod(type, url);
HttpResponse response = client.execute(request);
if (type == HttpType.POST && postParams != null) {
setPostParams(request, postParams);
}
return response.getEntity();
}

private void close() {
if (request != null && !request.isAborted()) {
request.abort();
}
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
}

/**
* 设置POST请求POST参数
*
* @param request
* POST请求
* @param postParams
* POST参数
* @throws Exception
*/
private void setPostParams(HttpRequestBase request,
Map<String, String> postParams) throws Exception {
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : postParams.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,
HTTP.UTF_8);
((HttpResponse) request).setEntity(entity);
}

private HttpRequestBase getMethod(HttpType type, String url)
throws Exception {
if (url == null || url.length() <= 0) {
throw new RuntimeException("请提供HTTP请求的URL地址");
}
String className = "org.apache.http.client.methods.Http"
+ type.getKey();
Class clazz = Class.forName(className);
return ((HttpRequestBase) clazz.getConstructor(String.class)
.newInstance(url));
}

/**
* 从输入流中读取数据并装换为字符串输出
*
* @param is
* 输入流
* @return 输入流读取出的字符串
* @throws Exception
*/
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
return sb.toString().trim();
}

public static void main(String[] args) throws Exception {
String url = "http://www.baidu.com";
String jsonString = new HttpUtil(url).getHttpResponseContent(
HttpType.GET, null);
System.out.println("Response String: " + jsonString);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的HttpClient是一种用于发送HTTP请求的开源Java库。它提供了许多功能,例如: 1. 支持HTTP协议的所有方法,例如GET、POST、PUT、DELETE等。 2. 支持HTTPS协议,并支持证书验证和安全协议。 3. 支持HTTP连接池,提高了请求的性能。 4. 支持请求和响应的拦截器,可以进行一些自定义的操作。 下面是一个简单的例子,用于发送一个GET请求: ``` // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpGet对象,将url作为参数传入构造函数 HttpGet httpGet = new HttpGet("http://www.example.com"); // 执行请求,获取响应 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); // 从响应中获取状态码 int statusCode = httpResponse.getStatusLine().getStatusCode(); // 从响应中获取响应体 String responseBody = EntityUtils.toString(httpResponse.getEntity()); // 关闭响应和HttpClient对象 httpResponse.close(); httpClient.close(); ``` 以上代码创建了一个默认的HttpClient对象,创建了一个HttpGet对象,并将url传入构造函数。然后,使用HttpClient对象执行请求,并获取响应。在响应中,我们可以获取状态码和响应体。最后,记得关闭响应和HttpClient对象,以释放资源。 除了GET请求,我们还可以使用HttpPost对象来发送POST请求,使用HttpPut对象来发送PUT请求,使用HttpDelete对象来发送DELETE请求等。每个请求对象都有不同的构造函数和方法,可以根据需要进行选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值