使用 Java 发送 HTTP 请求

本文介绍了如何在Java中使用Apache HttpClient库进行HTTP请求。包括GET和POST两种请求方式,详细讲解了携带key-value参数及JSON参数的POST请求,并提供了HTTPUtil工具类的封装示例。
摘要由CSDN通过智能技术生成


发送 HTTP 请求

在开发中,有时候会遇到需要调用现成的接口,我们就可以使用 Apache 提供的 Java 工具类 HttpClient。

一、引入 Maven 坐标

使用 Apache 的 HttpClient 需要引入相关的 Maven 坐标,Maven 坐标如下:

<!--        HttpClient 相关依赖-->
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient-cache -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.5.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.12</version>
        </dependency>

二、发送 GET 请求

不携带参数的 GET 请求的方法如下:

    /**
     * 功能描述: 使用 get 请求直接访问 url,不带参数
     *
     * @param url
     * @return: java.lang.String
     * @author: 路人WL
     * @date: 2020/4/27
     */
    public static String doGet(String url) throws Exception {
   
        // 创建 HttpClient 对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建访问地址
        URIBuilder uriBuilder = new URIBuilder(url);

        // 创建 http 对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 执行 get 请求
        CloseableHttpResponse httpResponse = client.execute(httpGet);
        // 接收回复的内容
        String result = null;
        if (httpResponse.getStatusLine
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值