在java中使用httpClient进行接口请求

本文详细介绍了如何在Java项目中使用ApacheHttpClient库进行GET和POST请求,包括依赖导入、参数传递、请求头设置以及GET和POST请求的具体实现,同时提到了JSON参数的处理方法。
摘要由CSDN通过智能技术生成

使用原生的httpClient的如何进行get和post请求

1.导入maven依赖

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version> <!-- 版本号可以根据您的需求进行调整 -->
    </dependency>
</dependencies>

由于在使用的过程中可能会需要解析json数据,因此也导入解析json的依赖,这里使用的是fastjson

<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.78</version> <!-- 版本号可以根据您的需求进行调整 -->
    </dependency>
</dependencies>

2.get请求方式

package org.example;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class Main {

    private static String baseUrl = "https://example.com/api/endpoint";
    public static void main(String[] args) {

        String userName = "abc";
        String passWord = "123456";
        String token = "123123";


        try {
            //对初始地址进行处理 处理后为https://example.com/api/endpoint?userName=abc&passWord=123456
            URIBuilder builder = new URIBuilder(baseUrl);
            builder.setParameter("userName", userName);
            builder.setParameter("passWord", passWord);


            //创建连接对象
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建HttpGet请求
            HttpGet httpGet = new HttpGet(builder.build().toString());

            // 添加请求头
            httpGet.addHeader("Authorization", token); // 替换为您的授权头信息

            CloseableHttpResponse response = null;

            // 发起请求
            try {
                response = httpClient.execute(httpGet);

                // 处理响应
                if (response.getStatusLine().getStatusCode() == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    System.out.println(responseBody);
                } else {
                    System.out.println("请求失败,状态码:" + response.getStatusLine().getStatusCode());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                //资源释放
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

3.post请求方式

package org.example;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class PostMain {

    private static String baseUrl = "https://example.com/api/endpoint";
    public static void main(String[] args) {

        String userName = "abc";
        String passWord = "123456";
        String token = "123123";


        try {
            //对初始地址进行处理 处理后为https://example.com/api/endpoint?userName=abc&passWord=123456
            URIBuilder builder = new URIBuilder(baseUrl);
            builder.setParameter("userName", userName);
            builder.setParameter("passWord", passWord);

            //创建连接对象
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建HttpGet请求
            HttpPost httpPost = new HttpPost(builder.build().toString());


            // 添加请求头
            httpPost.addHeader("Authorization", token); // 替换为您的授权头信息
            httpPost.setHeader("Content-type","application/json"); //设置请求参数为json 格式

            //设置请求体
            JSONObject requestJsonObject = new JSONObject();
            requestJsonObject.put("userName", userName);
            requestJsonObject.put("passWord", passWord);

            String requestBody = requestJsonObject.toString();
            StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            
            CloseableHttpResponse response = null;

            // 发起请求
            try {
                response = httpClient.execute(httpPost);

                // 处理响应
                if (response.getStatusLine().getStatusCode() == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    System.out.println(responseBody);
                } else {
                    System.out.println("请求失败,状态码:" + response.getStatusLine().getStatusCode());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                //资源释放
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

4.get与post的区别

在代码中,GET 请求使用 HttpGet 对象,将参数附加在 URL 后面;而 POST 请求使用 HttpPost 对象,将请求体中传输参数。

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值