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);
    }

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
毕业设计之springboot幼一起来约苗系统项目是一个基于Spring Boot框架开发的约苗系统,旨在帮助用户方便快捷地预约和管理疫苗接种。该项目提供了完整的源码和说明文档,包括系统架构设计、代码实现、数据库设计、接口文档等内容。该系统采用了Spring Boot框架,具有轻量级、快速开发和易于扩展的特点。项目源码中包含了系统的核心功能模块,包括用户管理、预约管理、疫苗信息管理等模块的实现代码。同时,项目还提供了详细的说明文档,包括项目架构设计思路、各个模块的功能描述、代码实现说明等内容,方便用户理解和学习系统的设计和实现思路。除了源码和说明文档外,该项目还提供了数据库设计文档和接口文档,方便用户了解系统的数据结构和接口调用方式。数据库设计文档详细描述了系统中各个数据表的结构和字段含义,接口文档描述了系统提供的各种API接口及其参数、返回结果等信息,方便用户在实际开发中进行调用和集成。综上所述,毕业设计之springboot幼一起来约苗系统项目为用户提供了完整的源码和说明文档,包括系统架构设计、代码实现、数据库设计、接口文档等内容,可供用户学习、参考和使用。希望该项目能够帮助到对Spring Boot框架和约苗系统感兴趣的用户,提升其开发能力和项目实践经验。
该JAVA毕业设计项目是一个基于SpringBoot框架开发的藏区特产销售平台,旨在为藏区特产提供一个在线销售平台,方便用户浏览和购买藏区特产。该项目包含了完整的源代码和详细的说明文档。该平台主要包括以下功能模块:1. 商品管理:用户可以在平台上浏览各种藏区特产商品,包括图片、价格、描述等信息。商家可以在平台上发布新的商品信息,并进行商品管理。2. 购物车:用户可以将感兴趣的商品添加到购物车中,方便统一管理和结算。3. 订单管理:用户可以查看自己的订单信息,包括已支付、未支付、已发货等状态,方便用户管理自己的购物记录。4. 用户管理:用户可以注册登录,在平台上查看个人信息、修改密码等操作。管理员可以管理用户信息和权限。5. 支付功能:集成了支付功能,用户可以通过平台进行在线支付,确保交易安全可靠。开发该平台使用了SpringBoot框架,集成了MyBatis作为持久层框架,并通过Thymeleaf模板引擎实现了页面展示和交互操作。另外,还使用了Spring Security实现用户权限管理和安全控制,保障了平台的安全性。该项目详细的说明文档包括了项目架构设计、模块功能介绍、代码逻辑解析、接口调用说明等内容,方便开发人员快速了解和上手该项目。同时,文档还包括了项目部署和运行的相关说明,方便用户进行部署运行。通过该项目,学习者可以了解SpringBoot框架在实际项目中的应用,以及项目的整体设计思路和开发流程,对类似电商平台的项目开发有很好的借鉴和参考作用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风水道人

写作不易且行且珍惜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值