介绍
HttpClient是 Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP协议的客户端编程工具包,并且它支持 HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如 Apache Jakarta上很著名的另外两个开源项目 Cactus和 HTMLUnit都使用了 HttpClient。本文使用的HttpClient版本为4.2。
HttpClient 特性
- 基于标准,纯净的java语言.实现了Http1.0和Http1.1
- 以可扩展的面向对象的结构实现了Http全部的方法 (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE).
- 支持HTTPS协议.
- 通过Http代理建立透明的连接.
- 利用CONNECT 方法通过Http代理建立隧道的https连接.
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos 认证方案.
- 插件式的自定义认证方案.
- 便携可靠的套接字工厂使它更容易的使用第三方解决方案.
- 连接管理器支持多线程应用.支持设置最大连接数,同时支持设置每个主机的最大连接数.发现并关闭过期的连接.
- Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
- 插件式的自定义Cookie策略.
- Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
- Response input streams to efficiently read the response body by streaming directly from the socket to the server.
- 在http1.0和http1.1中利用KeepAlive保持持久连接.
- 直接获取服务器发送的response code和 headers.
- 设置连接超时的能力.
- 实验性的支持http1.1 response caching.
代码示例
获取HttpClient示例:
public HttpClient getClient() {
HttpClient client = new DefaultHttpClient();// 获取HttpClient对象
return client;
}
HttpClient有多个实现,其中DefaultHttpClient为最常用的。
下面将展示如何使用get和post提交请求,还有如何处理查看response数据
使用get方法请求:
public void doGet(String uri) {// get方法提交
HttpGet getMethod = null;
getMethod = new HttpGet(uri);// 获取HttpGet对象,使用该对象提交get请求
exctueRequest(getMethod);//执行请求,获取HttpResponse对象
}
使用post方法请求
public void doPost(String uri,HttpEntity entity) {// post方法提交
HttpPost postMethod = null;
postMethod = new HttpPost(uri);
postMethod.setEntity(entity);//设置请求实体,例如表单数据
exctueRequest(postMethod); // 执行请求,获取HttpResponse对象
}
exctueRequest()方法详细说明
private HttpResponse exctueRequest(HttpRequestBase request){
HttpResponse response=null;
try {
log.debug("excute request:"+request.getURI());//获取请求uri
log.debug("-----------------------------------");
response=this.getClient().execute(request);//执行请求,获取HttpResponse对象
showResponse(response);//打印Response信息
int statuscode = response.getStatusLine().getStatusCode();//根据相应码处理URI重定向
if((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){
Header redirectLocation=response.getFirstHeader("Location");//从响应头中获取重定向的uri
String newuri=redirectLocation.getValue();
if((newuri!=null)||(!newuri.equals(""))){
log.debug("redirect to "+newuri);
request.setURI(new URI(newuri));//重新设置uri
response=this.getClient().execute(request);
showResponse(response);//打印response信息
}else {
log.debug("Invalid redirect");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
releaseConnection(request);//释放连接,无论成功与否都需要释放连接
}
return response;
}
打印响应信息
private void showResponse(HttpResponse response) throws ParseException,
IOException {
log.debug("requset result:");
log.debug(response.getStatusLine().toString());// 响应状态
log.debug("-----------------------------------");
Header[] heard = response.getAllHeaders();// 响应头
log.debug("response heard:");
for (int i = 0; i < heard.length; i++) {
log.debug(heard[i]);
}
log.debug("-----------------------------------");
HttpEntity entity = response.getEntity();// 响应实体/内容
log.debug("response content length:" + entity.getContentLength());
log.debug("response content:");
log.debug(EntityUtils.toString(entity));
}
释放连接
private void releaseConnection(HttpRequestBase request) {
if (request != null) {
request.releaseConnection();
}
}
完整代码
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private Log log = LogFactory.getLog(this.getClass());
public HttpClient getClient() {
HttpClient client = new DefaultHttpClient();// 获取HttpClient对象
return client;
}
private void releaseConnection(HttpRequestBase request) {
if (request != null) {
request.releaseConnection();
}
}
private void showResponse(HttpResponse response) throws ParseException,
IOException {
log.debug("requset result:");
log.debug(response.getStatusLine().toString());// 响应状态
log.debug("-----------------------------------");
Header[] heard = response.getAllHeaders();// 响应头
log.debug("response heard:");
for (int i = 0; i < heard.length; i++) {
log.debug(heard[i]);
}
log.debug("-----------------------------------");
HttpEntity entity = response.getEntity();// 响应实体/内容
log.debug("response content length:" + entity.getContentLength());
log.debug("response content:");
log.debug(EntityUtils.toString(entity));
}
public void doGet(String uri) {// get方法提交
HttpGet getMethod = null;
getMethod = new HttpGet(uri);// 获取HttpGet对象,使用该对象提交get请求
exctueRequest(getMethod);
}
public void doPost(String uri,HttpEntity entity) {// post方法提交
HttpPost postMethod = null;
postMethod = new HttpPost(uri);
postMethod.setEntity(entity);//设置请求实体,例如表单数据
exctueRequest(postMethod); // 执行请求,获取HttpResponse对象
}
private HttpResponse exctueRequest(HttpRequestBase request){
HttpResponse response=null;
try {
log.debug("excute request:"+request.getURI());
log.debug("-----------------------------------");
response=this.getClient().execute(request);//执行请求,获取HttpResponse对象
showResponse(response);
int statuscode = response.getStatusLine().getStatusCode();//处理重定向
if((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){
Header redirectLocation=response.getFirstHeader("Location");
String newuri=redirectLocation.getValue();
if((newuri!=null)||(!newuri.equals(""))){
log.debug("redirect to "+newuri);
request.setURI(new URI(newuri));
response=this.getClient().execute(request);
showResponse(response);
}else {
log.debug("Invalid redirect");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
releaseConnection(request);//释放连接
}
return response;
}
public static void main(String[] args) {
HttpClientUtil client = new HttpClientUtil();
client.doGet("http://www.baidu.com/s?wd=HttpClient");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();// 设置表格参数
formparams.add(new BasicNameValuePair("usrname", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity = null;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");//获取实体对象
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.doPost("http://localhost:8080/U2_project/login.do",uefEntity);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)