HttpClient远程使用大全

编程入门 行业动态 更新时间:2024-10-19 08:58:03

HttpClient远程使用<a href=https://www.elefans.com/category/jswz/34/1769146.html style=大全"/>

HttpClient远程使用大全

一 HttpClient简介

1.1 概述

HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。主要实现功能:

实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)

支持 HTTPS 协议

支持代理服务器(Nginx等)等

支持自动(跳转)转向。

1.2 案例工程介绍

1.2.1 工程截图

请求端:16-spt-http-request-demo  :7000     响应端:16-spt-httppush-demo :8082

1.2.2 引入依赖

    <!-- httpclient  --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><!-- fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>

注:SpringBoot的基本依赖配置,这里就不再多说了

二  实操实例Get方式

2.1 get无参数案例

1.消费者

@RestController
public class HttpClientController {@RequestMapping("/hc/api")public String getInfo() throws Exception {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Get请求HttpGet httpGet = new HttpGet("http://localhost:8082/get/noparam");String result="";// 响应模型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());result=EntityUtils.toString(responseEntity);System.out.println("响应内容为:" + result);}} 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();}}return result;}
}

2.服务者

@RestController
public class HttpClientController {@RequestMapping("/get/noparam")public String doGetNoParam(){return "ok 123!";}
}

截图如下: 

3.请求测试

 

更多推荐

HttpClient远程使用大全

本文发布于:2023-12-03 11:14:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1654743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大全   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!