在写网络程序的时候,经常会有从网址获取数据的需求,上一篇解析JSON就需要从百度获取天气数据,本文介绍一种Java发送http请求的工具–HttpClient。
##HttpClient的介绍
The most essential function of HttpClient is to execute HTTP methods. Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient. The user is expected to provide a request object to execute and HttpClient is expected to transmit the request to the target server return a corresponding response object, or throw an exception if execution was unsuccessful.
HttpClient最基本的功能就是执行http方法,执行http方法包括了一次或者几次HTTP请求和相应的变化,通常也是通过HttpClient来处理的。只要用户提供一个request的对象,HttpClient就会将用户的请求发送到目标服务器上,并且返回一个respone对象,如果没有执行成功将抛出一个异常。
通过文档的介绍我们可以知道,发送HTTP请求一般可以分为以下步骤
- 取得HttpClient对象
- 封装http请求
- 执行http请求
- 处理结果
其中可以发送的请求类型有GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS
HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS.
官方文档中的示例
//1.获得一个httpclient对象CloseableHttpClient httpclient =HttpClients.createDefault();//2.生成一个get请求HttpGet httpget =newHttpGet("http://localhost/");//3.执行get请求并返回结果CloseableHttpResponse response =httpclient.execute(httpget);try{ //4.处理结果}finally{ response.close();}
介绍一下最常用的HttpGet和HttpPost。
RESTful提倡,通过HTTP请求对应的POST、GET、PUT、DELETE来完成对应的CRUD操作。
所以本文介绍一下通过GET获取数据和POST提交数据的实现方法。
##发送HttpGet
先介绍发送HttpGet请求
/** * 发送HttpGet请求 * @param url * @return */ publicstaticString sendGet(String url){
//1.获得一个httpclient对象 CloseableHttpClient httpclient =HttpClients.createDefault(); //2.生成一个get请求 HttpGet httpget =newHttpGet(url); CloseableHttpResponse response =null; try{ //3.执行get请求并返回结果 response =httpclient.execute(httpget); }catch(IOExceptione1){ e1.printStackTrace(); } String result =null; try{ //4.处理结果,这里将结果返回为字符串 HttpEntity entity =response.getEntity(); if(entity !=null){ result =EntityUtils.toString(entity); } }catch(ParseException|IOException e){ e.printStackTrace(); }finally{ try{ response.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnresult; }
##发送HttpPost
发送HttpPost的方法和发送HttpGet很类似,只是将请求类型给位HttpPost即可。
代码如下
/** * 发送不带参数的HttpPost请求 * @param url * @return */ publicstaticString sendPost(String url){
//1.获得一个httpclient对象 CloseableHttpClient httpclient =HttpClients.createDefault(); //2.生成一个post请求 HttpPost httppost =newHttpPost(url); CloseableHttpResponse response =null; try{ //3.执行get请求并返回结果 response =httpclient.execute(httppost); }catch(IOExceptione){ e.printStackTrace(); } //4.处理结果,这里将结果返回为字符串 HttpEntity entity =response.getEntity(); String result =null; try{ result =EntityUtils.toString(entity); }catch(ParseException|IOException e){ e.printStackTrace(); } returnresult; }
##带参数的HttpPost
发送带参数的HttpPost
Many applications need to simulate the process of submitting an HTML form, for instance, in order to log in to a web application or submit input data. HttpClient provides the entity class UrlEncodedFormEntity to facilitate the process.
HttpClient通过UrlEncodedFormEntity,来提交带参数的请求
将需要提交的参数放在map里
代码如下
/** * 发送HttpPost请求,参数为map * @param url * @param map * @return */ publicstaticString sendPost(String url,Map<String, String>map){
CloseableHttpClient httpclient =HttpClients.createDefault(); List<NameValuePair>formparams =newArrayList<NameValuePair>(); for(Map.Entry<String, String>entry :map.entrySet()){
//给参数赋值 formparams.add(newBasicNameValuePair(entry.getKey(),entry.getValue())); } UrlEncodedFormEntity entity =newUrlEncodedFormEntity(formparams,Consts.UTF_8); HttpPost httppost =newHttpPost(url); httppost.setEntity(entity); CloseableHttpResponse response =null; try{ response =httpclient.execute(httppost); }catch(IOExceptione){ e.printStackTrace(); } HttpEntity entity1 =response.getEntity(); String result =null; try{ result =EntityUtils.toString(entity1); }catch(ParseException|IOException e){ e.printStackTrace(); } returnresult; }
##完整代码
完成代码如下,用到的jar包有httpclient-4.5.1.jar,httpcore-4.4.3.jar,依赖的jar有commons-logging-1.2.jar
注意是Apache HttpClient,不是commons-httpclient
importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importorg.apache.http.Consts;importorg.apache.http.HttpEntity;importorg.apache.http.NameValuePair;importorg.apache.http.ParseException;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;/** * @author GWCheng * */publicclassHttpUtil