Java工具类--通过HttpClient发送http请求

本文介绍了Java中使用HttpClient库发送HTTP请求的基本步骤,包括HttpGet和HttpPost的使用,以及如何处理带参数的HttpPost请求。HttpClient提供了模拟HTML表单提交的功能,使得数据提交变得简单。示例代码展示了HttpClient的使用,并给出了相关测试用例。
摘要由CSDN通过智能技术生成
                       

在写网络程序的时候,经常会有从网址获取数据的需求,上一篇解析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请求一般可以分为以下步骤

  1. 取得HttpClient对象
  2. 封装http请求
  3. 执行http请求
  4. 处理结果

其中可以发送的请求类型有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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值