SpringBoot项目调用HTTP接口5种方式你了解多少?

简介: SpringBoot项目调用HTTP接口5种方式你了解多少?

概述调用HTTP的几种方式:

1. 使用FeignClient调用:Feign是一个声明式的Web Service客户端,它使得编写HTTP客户端变得更简单。通过FeignClient,你可以在代码中直接调用HTTP接口,而不需要手动编写HTTP请求和响应的处理逻辑。

2. 使用RestTemplate调用:RestTemplate是Spring框架提供的用于访问RESTful服务的工具类。它提供了多种HTTP请求方法(如GET、POST、PUT、DELETE等),并支持自定义HTTP消息转换器以处理HTTP请求和响应。

3. 使用AsyncHttpClient调用:AsyncHttpClient是一个异步的HTTP客户端库,它支持异步执行HTTP请求并返回异步结果。使用AsyncHttpClient可以有效地提高应用程序的性能和响应速度。

4. 使用HttpURLConnection调用:HttpURLConnection是Java内置的用于访问HTTP服务的API。它提供了HTTP请求和响应的基本功能,如设置请求头、发送GET/POST请求、获取响应状态码和响应体等。

5. 使用hutool调用:hutool是一个Java工具库,它提供了一些方便的工具类和方法,包括HTTP相关的功能。通过hutool,你可以轻松地发送HTTP请求并获取响应结果。

1.使用FeignClient调用

2.使用RestTemplate调用

3.使用AsyncHttpClient调用

4.使用HttpURLConnection调用

1.GET请求
2.POST请求
3.上传文件
4.Stream请求

5.使用hutool调用

1.案例FeignClient

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <!-- <version>4.0.1</version> -->
</dependency>
 
//启动类:@EnableFeignClients
 
@FeignClient(name = "masterdata",url = "${url}")
public interface ISysUserClient {
 
    @GetMapping(value = "/masterdata/getSysUserById")
    public Map getSysUserById(@RequestParam("userId") String userId);
}

2.RestTemplate

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(1000);//单位为ms
        factory.setConnectTimeout(1000);//单位为ms
        return factory;
    }
}
 
 
//测试
 
@RestController
public class Test {
    @Resource
    private RestTemplate restTemplate;
 
    @GetMapping(value = "/save")
    public void save(String userId) {
        String url = "xxxxxx";
        Map map = new HashMap<>();
        map.put("name", "0000");
        String results = restTemplate.postForObject(url, map, String.class);
    }
  }

3.AsyncHttpClient

4.Apache HttpClient

  <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>
    </dependencies>
public class GetClient {
    /**
     * GET---无参测试
     */
    public void doGetTestOne(){
        //获得http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //创建get请求
        HttpGet httpGet = new HttpGet("https://www.cuit.edu.cn/");
        //响应模型
        CloseableHttpResponse response = null;
        try{
            //有客户端指定get请求
            response = client.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 (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                //释放资源
                if(client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * GET--有参测试
     */
    public void doGetTestWayOne(){
        //获得http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
 
        //参数
        StringBuilder params = new StringBuilder();
        try{
            params.append("name=").append(URLEncoder.encode("&","utf-8")).append("&").append("age=24");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        //创建Get请求
        HttpGet httpGet = new HttpGet("https://www.cuit.edu.cn/?" + params);
        //响应模型
        CloseableHttpResponse response = null;
        try{
            //配置信息
            RequestConfig config = RequestConfig.custom()
                    //设置连接超时时间
                    .setConnectTimeout(5000)
                    //设置请求超时时间
                    .setConnectionRequestTimeout(5000)
                    //socket读写超时时间
                    .setSocketTimeout(5000)
                    //设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true)
                    .build();
            //将上面的配置信息配入Get请求中
            httpGet.setConfig(config);
 
            //由客户端执行Get请求
            response = client.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,"utf-8"));
            }
 
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
    public void doGetTestWayTwo(){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        URI uri = null;
        try{
            ArrayList<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("name","10"));
            params.add(new BasicNameValuePair("age","18"));
            //这里设置uri信息,并将参数集合放入uri;
            //注: 这里也支持一个键值对一个键值对地往里面方setParameter(String key, String value)
            uri = new URIBuilder().setScheme("http").setHost("www.cuit.edu.cn")
//                    .setPort(12345).setPath("/xw")
                    .setParameters(params).build();
            System.out.println(uri);
 
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        //创建httpGet请求
        HttpGet httpGet = new HttpGet(uri);
 
        //创建响应模型
        CloseableHttpResponse response = null;
        try{
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000)
                    .setRedirectsEnabled(true).build();
 
            httpGet.setConfig(config);
            response = client.execute(httpGet);
 
            HttpEntity entity = response.getEntity();
            System.out.println("响应状态码:"+response.getStatusLine());
 
            System.out.println("响应内容长度:"+entity.getContentLength());
            System.out.println("响应内容:"+EntityUtils.toString(entity,"utf-8"));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //测试
    public static void main(String[] args) {
        //new GetClient().doGetTestOne();
        //new GetClient().doGetTestWayOne();
        new GetClient().doGetTestWayTwo();
    }
}
public class PostClient {
 
    /**
     * POST 无参
     */
    public void doPostTestOne(){
        //获得http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //创建Post请求
        HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/index.htm");
        //创建响应模型
        CloseableHttpResponse response = null;
        try{
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println("响应状态码:"+response.getStatusLine());
            System.out.println("响应内容长度:"+entity.getContentLength());
            System.out.println("响应内容:"+ EntityUtils.toString(entity,"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if (client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
    /**
     * POST 有参
     */
    public void doPostTestFour(){
        //获的http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
 
        //参数
        StringBuilder params = new StringBuilder();
        try{
            //字符数据最好encoding; 这样一来, 某些特殊字符才嗯那个传过去(如:某人的名字就是"&",不encoding,传不过去)
            params.append("phone=").append(URLEncoder.encode("admin","utf-8"));
            params.append("&");
            params.append("password=admin");
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        //创建post请求
        HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/?" + params);
 
        //设置ContentType(注:如果只是传入普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        //响应模型
        CloseableHttpResponse response = null;
        try{
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println("状态码:"+response.getStatusLine());
            System.out.println("响应内容长度: "+entity.getContentLength());
            System.out.println("响应内容: "+entity);
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * POST---有参测试(对象参数)
     */
    public void doPostTestTwo(){
        //获取Http客户端
        CloseableHttpClient client = HttpClientBuilder.create().build();
 
        //创建Post请求
        HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/index.htm");
        //User user = new User();
        //user.setName("潘晓婷");
        //user.setAge(18);
        //user.setGender("女");
        //user.setMotto("姿势要优雅~");
        // 我这里利用阿里的fastjson,将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        //String jsonString = JSON.toJSONString(user);
        String jsonString = "";
        StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        CloseableHttpResponse response = null;
        try{
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println("状态码:"+response.getStatusLine());
            System.out.println("响应内容长度:"+entity.getContentLength());
            System.out.println("响应内容:"+EntityUtils.toString(entity,"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if (client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
    public static void main(String[] args) {
        //new PostClient().doPostTestOne();
        //new PostClient().doPostTestFour();
        new PostClient().doPostTestTwo();
    }
}
public class FileClient {
    /**
     * 发送文件
     注:如果想要灵活方便的传输文件的话,
     *    除了引入org.apache.httpcomponents基本的httpclient依赖外
     *    再额外引入org.apache.httpcomponents的httpmime依赖。
     *    追注:即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。
     */
    public void test4(){
 
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/file");
 
        CloseableHttpResponse response = null;
        try{
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            //第一个文件
            String fileKey = "files";
            File file1 = new File("D:\\图片\\《Valorant》3440x1440带鱼屏游戏壁纸_彼岸图网.jpg");
            /*
            防止服务端收到的文件名乱码. 我们这里可以先将文件名URLEncode, 然后服务端拿到文件后URLDecode
            文件名其实是放在请求头的Content-Disposition中 如其值form-data; name="files"; filename="头像.jpg"
             */
            multipartEntityBuilder.addBinaryBody(fileKey,file1, ContentType.DEFAULT_BINARY, URLEncoder.encode(file1.getName(),"utf-8"));
 
            //其他参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
            ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
            multipartEntityBuilder.addTextBody("name","等沙利文",contentType);
            multipartEntityBuilder.addTextBody("age","25",contentType);
 
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity!=null){
                System.out.println("状态码:"+response.getStatusLine());
                System.out.println("响应内容长度:"+entity.getContentLength());
                System.out.println("响应内容:"+ EntityUtils.toString(entity,"utf-8"));
            }
            /*
            File file1 = new File("D:\\图片\\XXX.jpg");
            multipartEntityBuilder.addBinaryBody(fileKey,file1);
             */
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        new FileClient().test4();
    }
}
 
public class StreamClient {
    /**
     * 发送流
     */
    public void test5(){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("https://www.baidu.com/index.htm");
        CloseableHttpResponse response = null;
        try {
            ByteArrayInputStream is = new ByteArrayInputStream("流~".getBytes(StandardCharsets.UTF_8));
            InputStreamEntity ise = new InputStreamEntity(is);
            httpPost.setEntity(ise);
 
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println("响应状态码:"+response.getStatusLine());
            if (entity!=null){
                System.out.println("响应内容长度:"+entity.getContentLength());
                System.out.println("响应内容:"+ EntityUtils.toString(entity,StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (client!=null){
                    client.close();
                }
                if (response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        new StreamClient().test5();
    }
}

5.hutool

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.5.1</version>
</dependency>
public static void main(String[] args){
        // 1. 创建HttpRequest对象 - 指定好 url 地址
        HttpRequest httpRequest = new HttpRequest("http://ip:port/test/");
        // 2. 设置请求方式,默认是GET请求
        httpRequest.setMethod(Method.GET);
        // 3. 设置请求参数   可通过 form表单方法 设置
        //    form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿传
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("username","00");
        httpRequest.form(paramsMap);
        httpRequest.form("password", "123456");
        httpRequest.form("username","ooo");
        // 4. 设置请求头
        //    请求头同样可以逐一设置,也可以封装到map中再统一设置
        //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
        httpRequest.header("x-c-authorization","yourToken");
        // 5. 执行请求,得到http响应类
        HttpResponse execute = httpRequest.execute();
 
        // 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
        boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
        System.out.println(ok);
        List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
        cookies.forEach(System.out::println); // 如果为空不会遍历的
        String body = execute.body();   // 获取响应主体
        System.out.println(body);
    }
相关文章
|
11天前
|
前端开发 JavaScript Java
SpringBoot项目部署打包好的React、Vue项目刷新报错404
本文讨论了在SpringBoot项目中部署React或Vue打包好的前端项目时,刷新页面导致404错误的问题,并提供了两种解决方案:一是在SpringBoot启动类中配置错误页面重定向到index.html,二是将前端路由改为hash模式以避免刷新问题。
54 1
|
10天前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的在线考试系统(含教程&源码&数据库数据)
本文介绍了一个基于Spring Boot和Vue.js实现的在线考试系统。随着在线教育的发展,在线考试系统的重要性日益凸显。该系统不仅能提高教学效率,减轻教师负担,还为学生提供了灵活便捷的考试方式。技术栈包括Spring Boot、Vue.js、Element-UI等,支持多种角色登录,具备考试管理、题库管理、成绩查询等功能。系统采用前后端分离架构,具备高性能和扩展性,未来可进一步优化并引入AI技术提升智能化水平。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的在线考试系统(含教程&源码&数据库数据)
|
3天前
|
Java 关系型数据库 数据库连接
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第3天】Spring Boot项目中数据库连接问题可能源于配置错误或依赖缺失。YAML配置文件的格式不正确,如缩进错误,会导致解析失败;而数据库驱动不匹配、连接字符串或认证信息错误同样引发连接异常。解决方法包括检查并修正YAML格式,确认配置属性无误,以及添加正确的数据库驱动依赖。利用日志记录和异常信息分析可辅助问题排查。
22 10
|
2天前
|
Java 关系型数据库 MySQL
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第4天】本文分析了Spring Boot应用在连接数据库时可能遇到的问题及其解决方案。主要从四个方面探讨:配置文件格式错误、依赖缺失或版本不兼容、数据库服务问题、配置属性未正确注入。针对这些问题,提供了详细的检查方法和调试技巧,如检查YAML格式、验证依赖版本、确认数据库服务状态及用户权限,并通过日志和断点调试定位问题。
|
7天前
|
JavaScript 前端开发 Java
SpringBoot项目的html页面使用axios进行get post请求
SpringBoot项目的html页面使用axios进行get post请求
23 6
|
8天前
|
消息中间件 Java Kafka
springboot项目启动报错-案例情景介绍
springboot项目启动报错-案例情景介绍
17 2
|
9天前
|
SQL JSON Java
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
本文为Spring Boot增删改查接口的小白入门教程,介绍了项目的构建、配置YML文件、代码编写(包括实体类、Mapper接口、Mapper.xml、Service和Controller)以及使用Postman进行接口测试的方法。同时提供了SQL代码和完整代码的下载链接。
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
|
9天前
|
存储 前端开发 Java
springboot文件上传和下载接口的简单思路
本文介绍了在Spring Boot中实现文件上传和下载接口的简单思路。文件上传通过`MultipartFile`对象获取前端传递的文件并存储,返回对外访问路径;文件下载通过文件的uuid名称读取文件,并通过流的方式输出,实现文件下载功能。
springboot文件上传和下载接口的简单思路
|
2天前
|
存储 NoSQL Java
Spring Boot项目中使用Redis实现接口幂等性的方案
通过上述方法,可以有效地在Spring Boot项目中利用Redis实现接口幂等性,既保证了接口操作的安全性,又提高了系统的可靠性。
6 0
|
10天前
|
Java 网络架构
springboot配合thymeleaf,调用接口不跳转页面只显示文本
springboot配合thymeleaf,调用接口不跳转页面只显示文本
38 0

热门文章

最新文章

下一篇
无影云桌面