HttpClient_入门案例

本文介绍了HttpClient,一种用于发起HTTP请求的组件,支持GET、POST等多种请求方式。通过详细步骤展示了如何发起Get和带参数的Get请求,并提供了执行日志。还提及了带参数的POST请求的流程。
摘要由CSDN通过智能技术生成

一、HttpClient

1.1、 前台系统访问后台接口的方式

两个系统间如何互相访问?两个tomcat上的项目如何互相访问

采用HttpClient实现跨系统的接口调用。

1.2、 什么是HttpClient

在这里插入图片描述
官网:http://hc.apache.org/index.html
现在也叫:HttpComponents
在这里插入图片描述
特点:

  1. HttpClient别名:HttpComponents
  2. HttpClient可以发送get、post、put、delete、…等请求

1.3、 HttpClient入门案例

pom.xml和application.properties文件
导入maven坐标

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>

1.3.1、 发起Get请求

  • 流程

1.创建一个客户端 CloseableHttpClient

2.创建一个get方法请求实例 HttpGet

3.发送请求 execute

4.获取响应的头信息

5.获取响应的主题内容

6.关闭响应对象

使用HttpClient发起Get请求的案例代码:

/**
 * 使用HttpClient发起Get请求,请求百度
 */
public class DoGETParam {
   

    public static void main(String[] args) throws Exception {
   
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建URI对象,并且设置请求参数
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
        
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);

        // HttpGet get = new HttpGet("http://www.baidu.com/s?wd=java");
        
        CloseableHttpResponse response = null;
        try {
   
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为2
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值