您的位置:首页 > 理论基础 > 计算机网络

HttpClient 组件学习使用

2016-06-06 22:12 537 查看

HttpClient 组件学习使用

背景介绍

目前在很多java开发中都需要使用到发送http请求,虽然java.net包提供了发送http请求的接口和类但是使用原生不够灵活和比较复杂,因为为了更便捷的使用http请求apache组织提供了开源HttpClient组件可以让我们很方便的来发送http请求。

The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.
Although the java.net package provides basic functionality for accessing resources via HTTP, it doesn't provide the full flexibility or functionality needed by many applications. HttpClient seeks to fill this void by providing an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations.
Designed for extension while providing robust support for the base HTTP protocol, HttpClient may be of interest to anyone building HTTP-aware client applications such as web browsers, web service clients, or systems that leverage or extend the HTTP protocol for distributed communication.


Features 特性:

1、Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
2、Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
3、Supports encryption with HTTPS (HTTP over SSL) protocol.
4、Transparent connections through HTTP proxies.
5、Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
6、Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO, Kerberos authentication schemes.
7、Plug-in mechanism for custom authentication schemes.
8、Pluggable secure socket factories, making it easier to use third party solutions
9、Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
10、Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
11、Plug-in mechanism for custom cookie policies.
12、Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
13、Response input streams to efficiently read the response body by streaming directly from the socket to the server.
14、Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
15、Direct access to the response code and headers sent by the server.
16、The ability to set connection timeouts.
17、Support for HTTP/1.1 response caching.
18、Source code is freely available under the Apache License.


quick start 基本使用

Get请求

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}


Post请求

HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);

try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}


使用HttpClient基本步骤

1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接


自己定义的HttpUtils

public class HttpUtils {

/**
* 发送get 请求
* @param url           get请求地址
* @param paramMap      get请求参数
* @return
*/
public static HttpResponse sendGet(final String url,
Map<String, String> paramMap) {
HttpResponse response = null;
HttpClient client = HttpClients.createDefault();
StringBuilder stringBuilder = new StringBuilder(url);
if (paramMap != null && !paramMap.isEmpty()) {
stringBuilder.append("?");
for (Entry<String, String> entry : paramMap.entrySet()) {
stringBuilder.append(entry.getKey()).append("=")
.append(entry.getValue()).append("&");
}
}
String newUrl = stringBuilder.substring(0, stringBuilder.length() - 1);
HttpGet request = new HttpGet(newUrl);
try {
response = client.execute(request);
} catch (Exception e) {
}
return response;
}

/**
* 发送post请求(form表单形式提交)
* @param url           post请求地址
* @param paramMap      post请求参数
* @return
*/
public static HttpResponse sendPostByForm(final String url,
Map<String, String> paramMap) {
HttpResponse response = null;
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();

if (paramMap != null && !paramMap.isEmpty()) {
for (Entry<String, String> entry : paramMap.entrySet()) {
urlParameters.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}
}
// 发送执行请求
try {
response = client.execute(post);
} catch (Exception e) {

}
return response;
}

/**
* 发送post请求(json对象格式提交数据例如ajax提交,contentType="application/json")
* @param url               post请求地址
* @param stringJson        javabean对象对应json对象(推荐使用Gson来转换)
* @return
*/
public static HttpResponse sendPostByJson(final String url,
final String stringJson) {
HttpResponse response = null;
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);

post.addHeader(HTTP.CONTENT_TYPE, "application/json");

StringEntity stringEntity;
try {
stringEntity = new StringEntity(stringJson);
stringEntity.setContentType("text/json");
stringEntity.setContentEncoding(
new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(stringEntity);
// 发送执行请求
response = client.execute(post);
} catch (Exception e) {

}
return response;

}

/**
* 判断发送请求响应是否成功
* @param response          响应内容
* @return
*/
public static boolean isSendSuccess(HttpResponse response) {
if (response != null) {
int code = response.getStatusLine().getStatusCode();
return 200 == code;
}
return false;
}
/**
* 获得响应状态码
* @param response          响应内容
* @return
*/
public static int getStatusCode(HttpResponse response) {
if (response != null) {
return response.getStatusLine().getStatusCode();
}
return 0;
}

/**
* 获得响应内容Content
* @param response          响应内容
* @return
*/
public static String getResponseContent(HttpResponse response) {
StringBuffer result = new StringBuffer();
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
}
return result.toString();
}
/**
* @param response          响应内容
* @return
*/
public static String getEntityContent(HttpResponse response) {
HttpEntity httpEntity = response.getEntity();
String entityContent = null;
try {
entityContent = EntityUtils.toString(httpEntity, "utf-8");
} catch (Exception e) {
}
return entityContent;
}
}


可视化Http请求工具推荐

1、chrome浏览器下的postman插件
2、firefox下RESTClient插件
3、firefox下HttpRequester插件
备注:都非常的棒


参考

http://hc.apache.org/index.html

http://www.cnblogs.com/ITtangtang/p/3968093.html

http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html

http://blog.csdn.net/wangpeng047/article/details/19624529

https://www.ibm.com/developerworks/cn/opensource/os-httpclient/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  apache java