HTTP 协议可以说是现在 Internet 上使用得最多的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。
而HttpClient就是一个基于HTTP协议的RPC,HttpClient是Apache Jakarta Common下的子项目,它的目的在于发送、接受 HTTP 信息。
一、环境

在pom.xml中引入HttpClient的依赖
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.1</version>
</dependency>
引入此依赖的目的是,会用到“将对象转化为json字符串的功能
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version>
</dependency>
public class User {private String name;private Integer age;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "User [name=" + name + ", age=" + age + ", sex=" + sex + "]";}
}

详细使用例子如下

一、GET无参
发送端

 public static void sendGetOne() {//获取http客户端CloseableHttpClient httpClient = HttpClientBuilder.create().build();//创建httpGet请求HttpGet httpGet = new HttpGet("http://localhost:8080/httpclient_service/test1.action");//响应模型CloseableHttpResponse response = null;try {//由客户端发送Get请求response = httpClient.execute(httpGet);//从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态:" + response.getStatusLine());if(responseEntity != null) {System.out.println("响应内容长度:"+responseEntity.getContentLength());System.out.println("响应内容:" + EntityUtils.toString(responseEntity));}}catch(Exception e) {}finally {try {if(httpClient != null) {httpClient.close();}if(response != null) {response.close();}}catch(Exception e) {}}}

接收端

@RequestMapping("/test1")
@ResponseBody
public User test1() {User user = new User("张三",18,"男");return user;
}

返回结果

响应状态为:HTTP/1.1 200 OK
响应内容长度为:-1
响应内容为:{"name":"张三","age":18,"sex":"男"}

二、GET有参拼接URL
发送端

public static void doGetTestWayOne() {// 获得Http客户端CloseableHttpClient httpClient = HttpClientBuilder.create().build();// URL参数StringBuffer params = new StringBuffer();try {params.append("name=" + URLEncoder.encode("李四", "utf-8"));params.append("&");params.append("age=24");params.append("&");params.append("sex=女");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}// 创建httpGet请求HttpGet httpGet = new HttpGet("http://localhost:8080/httpclient_service/test2.action" + "?" + params);// 响应模型CloseableHttpResponse response = null;try {// 配置信息RequestConfig requestConfig = RequestConfig.custom()// 设置连接超时时间(单位毫秒).setConnectTimeout(3000)// 设置请求超时时间(单位毫秒).setConnectionRequestTimeout(3000)// socket读写超时时间(单位毫秒).setSocketTimeout(3000)// 设置是否允许重定向(默认为true).setRedirectsEnabled(true).build();// 将上面的配置信息 注入到Get请求里httpGet.setConfig(requestConfig);// 由客户端执行Get请求response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度:" + responseEntity.getContentLength());System.out.println("响应内容:" + EntityUtils.toString(responseEntity));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}
}

接收端

@RequestMapping("/test2")
@ResponseBody
public User test2(String name,Integer age,String sex) {User user = new User(name,age,sex);return user;
}

返回结果

响应状态为:HTTP/1.1 200 OK
响应内容长度为:-1
响应内容为:{"name":"李四","age":24,"sex":"女"}

三、GET有参使用URI获得HttpGetL
发送端

public static void doGetTestWayTwo() {//获取http客户端CloseableHttpClient httpClient = HttpClientBuilder.create().build();//参数URI uri = null;try {//将参数放入键值对类NameValuePair中,在放入集合中List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("name","王麻子"));params.add(new BasicNameValuePair("age", "35"));params.add(new BasicNameValuePair("sex", "男"));//设置uri信息,并将参数集合放入uri;//注:这里也支持一个键值对一个键值对地往里面放setParameter(String key,String value)uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).setPath("/httpclient_service/test2.action").setParameters(params).build();}catch(Exception e) {}//创建git请求HttpGet httpGet = new HttpGet(uri);//响应模型CloseableHttpResponse response = null;try {//配置信息RequestConfig requestConfig = RequestConfig.custom()// 设置连接超时时间(单位毫秒).setConnectTimeout(5000)// 设置请求超时时间(单位毫秒).setConnectionRequestTimeout(5000)// socket读写超时时间(单位毫秒).setSocketTimeout(5000)// 设置是否允许重定向(默认为true).setRedirectsEnabled(true).build();// 将上面的配置信息 运用到这个Get请求里httpGet.setConfig(requestConfig);// 由客户端执行(发送)Get请求response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度:" + responseEntity.getContentLength());System.out.println("响应内容:" + EntityUtils.toString(responseEntity));}}catch(Exception e) {}finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}}

接收端

@RequestMapping("/test2")
@ResponseBody
public User test2(String name,Integer age,String sex) {User user = new User(name,age,sex);return user;
}

返回结果

响应状态:HTTP/1.1 200 OK
响应内容长度:-1
响应内容:{"name":"王麻子","age":35,"sex":"男"}

四、POST无参
发送端

public static void doPostTestOne() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求HttpPost httpPost = new HttpPost("http://localhost:8080/httpclient_service/test3.action");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度:" + responseEntity.getContentLength());System.out.println("响应内容:" + EntityUtils.toString(responseEntity));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}
}

接收端

@RequestMapping(value ="/test3",method = RequestMethod.POST)public String test3() {return "这个post请求没有任何参数";}

返回结果

响应状态:HTTP/1.1 404 Not Found
响应内容长度:1098
响应内容:<!DOCTYPE html><html><head><title>Apache Tomcat/8.0.9 - Error report</title><style type="text/css">H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}.line {height: 1px; background-color: #525D76; border: none;}</style> </head><body><h1>HTTP Status 404 - /httpclient_service/这个post请求没有任何参数</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>/httpclient_service/这个post请求没有任何参数</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><hr class="line"><h3>Apache Tomcat/8.0.9</h3></body></html>

五、POST有参(普通参数)
发送端

public static void doPostTestFour() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 参数StringBuffer params = new StringBuffer();try {// 字符数据最好encoding以下;params.append("name=" + URLEncoder.encode("李斯特", "utf-8"));params.append("&");params.append("age=55");params.append("&");params.append("sex=男");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}// 创建Post请求HttpPost httpPost = new HttpPost("http://localhost:8080/httpclient_service/test4.action" + "?" + params);// 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)httpPost.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度:" + responseEntity.getContentLength());System.out.println("响应内容:" + EntityUtils.toString(responseEntity));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}
}

接收端

@RequestMapping(value ="/test4",method = RequestMethod.POST)
@ResponseBody
public User test4(String name,Integer age,String sex) {User user = new User(name,age,sex);return user;
}

返回结果

响应状态为:HTTP/1.1 200 OK
响应内容长度为:-1
响应内容为:{"name":"李斯特","age":55,"sex":"男"}

六、POST有参(对象参数)
发送端

public static void doPostTestTwo() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求HttpPost httpPost = new  HttpPost("http://localhost:8080/httpclient_service/test5.action");User user = new User();user.setName("潘晓婷");user.setAge(18);user.setSex("女");// 我这里利用阿里的fastjson,将Object转换为json字符串;// (需要导入com.alibaba.fastjson.JSON包)String jsonString = JSON.toJSONString(user);System.out.println("jsonString:"+jsonString);StringEntity entity = new StringEntity(jsonString, "UTF-8");// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中httpPost.setEntity(entity);httpPost.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}
}

接收端

@RequestMapping(value ="/test5",method = RequestMethod.POST)
@ResponseBody
public User test5(@RequestBody User user) {return user;
}

返回结果

jsonString:{"age":18,"name":"潘晓婷","sex":"女"}响应状态为:HTTP/1.1 200 OK
响应内容长度为:-1
响应内容为:{"name":"潘晓婷","age":18,"sex":"女"}

七、POST有参(对象参数+普通参数)
发送端

public static void doPostTestThree() {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求// 参数URI uri = null;try {// 将参数放入键值对类NameValuePair中,再放入集合中List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("flag", "4"));params.add(new BasicNameValuePair("meaning", "这是什么鬼?"));// 设置uri信息,并将参数集合放入uri;// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).setPath("/httpclient_service/test6.action").setParameters(params).build();} catch (URISyntaxException e1) {e1.printStackTrace();}HttpPost httpPost = new HttpPost(uri);// HttpPost httpPost = new// HttpPost("http://localhost:12345/doPostControllerThree1");// 创建user参数User user = new User();user.setName("潘晓婷");user.setAge(18);user.setSex("女");// 将user对象转换为json字符串,并放入entity中StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中httpPost.setEntity(entity);httpPost.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}
}
}

接收端

@RequestMapping(value ="/test6",method = RequestMethod.POST)@ResponseBodypublic User test6(@RequestBody User user,Integer flag,String meaning) {user.setName(user.getName() +meaning +flag );return user;}

返回结果

响应状态为:HTTP/1.1 200 OK
响应内容长度为:-1
响应内容为:{"name":"潘晓婷这是什么鬼?4","age":18,"sex":"女"}

RPC(1)HttpClient详细使用(含例子)相关推荐

  1. RPC(1)HttpClient详细使用 含demo

    HTTP 协议可以说是现在 Internet 上使用得最多的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源. 而HttpClient就是一个基于HTTP协议的RPC, ...

  2. hive 如何将数组转成字符串_Hive函数大全(含例子)之字符串函数(String Functions)...

    字符串函数 String Functions ascii(string str) 返回结果: 返回字符串str首字母的十进制ascii码返回类型: intselect ascii('ABC'); -- ...

  3. mybatis-generator生成带中文注释POJO类的超详细教程含代码和图解

    mybatis-generator生成带中文注释POJO类的超详细教程含代码和图解 mybatis-generator自动生成带中文注释POJO类和增删改查,idea和eclipes都可以使用 MyC ...

  4. 一起实现RPC,超详细~~~ 第一篇

    一起实现RPC,超详细!!! 第一篇 一个简单的RPC通信逻辑如下: 服务端暴露其要提供服务的接口 客户端通过动态代理调用服务端的接口方法,通过代理将要传输的信息发送到服务端(代理是为了让客户端不去关 ...

  5. RPC远程调用(RMI的方式实现RPC、HttpClient实现RPC远程调用)

    RPC是什么? 2.3RPC实现的技术: 3:RMI实现RPC远程调用: 3.1RMI介绍 3.2RMI实现vip访问orders 3.2.1开发服务生产者(provider) 3.2.1.1创建or ...

  6. 从零开始写一个RPC框架的详细步骤

    http://blog.csdn.net/liu88010988/article/details/51547592 定位 所谓定位就是回答几个问题,我出于什么目的要写一个框架,我的这个框架是干什么的, ...

  7. VLC视频播放器原理详细分析含TS流格式分析

    vlc是一个功能强大的玩意,能做很多有意思的事情. 最简单的,从界面打开一个文件播放,也可以在命令行下使用,如 C:\Program Files\VideoLAN\VLC>vlc.exe tes ...

  8. MACD详细计算方法及例子

    MACD对技术流投资者的重要性不言而喻.然而,很多资料对其详细算法都语焉不详.尤其是第一天和第二天的MACD的处理方式,很多说法有差别.今天查了查资料,终于搞清楚了其计算方法.用该方法计算理工检测,法 ...

  9. HttpClient详细使用示例

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提供了访 ...

最新文章

  1. 19岁大学生网恋被骗318万!见到“女神”后傻了,对方竟有200斤!
  2. matlab扩充内存,matlab扩大内存的方法
  3. 游戏上线... 记录下...
  4. [Step By Step]SAP HANA PAL多元线性回归预测分析Linear Regression实例FORECASTWITHLR(预测)...
  5. 博途v14电脑要求_博途v15对电脑配置要求
  6. 基于IM实现直播礼物效果
  7. 三菱Q系列总线型项目程序全套,三菱PLC程序+proface触摸屏双屏+电气图纸+程序注释规划表
  8. Kubeadm初始化Kubernetes集群
  9. js 禁止鼠标菜单键及键盘快捷键
  10. matlab hurst,基于Matlab的Hurst指数
  11. python布尔值使用_Python布尔值--True和False
  12. C++编译原理,O1 O2 O3编译优化
  13. SAP 记账凭证 更改 冲销
  14. 水果食用大全 -- 果品食疗 - 雪梨
  15. PTA L2-048 寻宝图
  16. 论创业者的幸存者偏差
  17. #38 WARNING(SPCODD-38): ERROR(SPCODD-47):
  18. 无缝切地图的3D赛车游戏火了,小哥花16个月用JS打造,浏览器免费就能玩
  19. 漫步凸分析十一——分离定理
  20. 网站快照被篡改劫持怎么办

热门文章

  1. 也谈智能手机游戏开发中的分辨率自适应问题
  2. redis清空所有数据 php
  3. android 高通分区表,高通msm8994平台的NV到底是储存在哪个分区?
  4. 【手把手带你学习神经机器翻译--代码篇】
  5. CC2530--串口实验的回显
  6. 影评分析第2篇 《博人传-火影忍者新时代》透过2W条评论看动漫
  7. 2020年:风雨兼程,不负韶华,注定是不平凡的一年
  8. 知识?一文解析币圈一级二级市场 原来币圈居然这么多要知道的
  9. The error may involve defaultParameterMap ### The error occurred while setting paramete
  10. 3.内网渗透之reGeorg+Proxifier