原文http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html
1.简介
HttpClient最重要的作用是执行http方法。处理一个http方法会涉及一个或者多个http request/http response之间的交换,这些都是在内部由httpclient执行。当用户向服务器发送一个request对象,本质是由httpclient传输给目标服务器,返回一个对应的response对象,如果不成功时返回一个异常。
request的处理过程:
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { <...> } finally { response.close(); }
2.主要功能
-
实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
-
支持自动转向
-
支持 HTTPS 协议
-
支持代理服务器等
3.使用HttpClient的基本流程(读取网页内容)
首先创建一个HttpClient(Http客户端)实例,之后确定提交的方法(get/post),最后在实例上执行提交的方法。
/**
* 读取网页内容
*/
HttpCilent httpclient = new HttpClient();
HttpMethod httpMethod = new GetMethod("Http://java.sun.com");
//post方法
//HttpMethod httpMethod = new PostMethod("Http://java.sun.com");
//get方法
httpClient.executeMethod(httpMethod);
//打印服务器返回的状态
System.out.println(method.getStatusLine());
//打印返回的信息
System.out.println(method.getResponseBodyAsString());
//释放连接
method.releaseConnection();
4.访问接口
一般步骤:
创建一个HttpClient对象;
构造http请求对象;
执行HttpClient对象的execute方法,将Http请求对象作为该方法的参数
读取execute方法返回的HttpResponse结果并解析
释放连接
public void urlPostJson(String url,String desc,String json) {
log.info("-----------------------------"+desc+" Request: " + json);
HttpClient client = new HttpClient(); //创建HTTPClient对象
client.getHostConfiguration().setProxy("127.0.0.1", 5689);
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);//
client.setConnectionTimeout(3000);
client.getParams().setSoTimeout(3000);// client.setTimeout(1000);
client.getParams().setConnectionManagerTimeout(1000);
PostMethod method = new PostMethod(url);//确定http请求方法
try {
// method.setRequestHeader("Content-Type", " application/json; charset=UTF-8");
method.setRequestBody(new ByteArrayInputStream(json.getBytes("UTF-8")));
// method.setRequestBody(json);
int status = client.executeMethod(method);//执行方法
String res=method.getResponseBodyAsString();//获取返回对象
log.info(" status:"+status+" Resonse: "+res);
} catch (IOException e) {
log.error("HttpClient.executeMethod(postMethod) IOException!",e);
}finally{
if (method != null) {
method.releaseConnection();
}
}
}