当前位置: 代码网 > it编程>编程语言>Java > SpringBoot调用外部接口的几种方式

SpringBoot调用外部接口的几种方式

2024年10月25日 Java 我要评论
使用feignclient调用feignclient调用大多用于微服务开发中,各服务之间的接口调用。它以java接口注解的方式调用http请求,使服务间的调用变得简单1、在使用方引入依赖<!--

使用feignclient调用

feignclient调用大多用于微服务开发中,各服务之间的接口调用。它以java接口注解的方式调用http请求,使服务间的调用变得简单

1、在使用方引入依赖

<!-- feign注解 这里openfeign的版本要和自己使用的springboot匹配-->
<dependency>
    <groupid>org.springframework.cloud</groupid>
    <artifactid>spring-cloud-starter-openfeign</artifactid>
    <!-- <version>4.0.1</version> -->
</dependency>

2、服务接口调用方

2.1、在启动类上加上@enablefeigncliens注解

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cloud.openfeign.enablefeignclients;

@springbootapplication
@enablefeignclients
public class studyfeignapplication {

    public static void main(string[] args) {
        springapplication.run(studyfeignapplication.class, args);
        system.out.println("项目启动成功");
    }

}

2.2、编写feign接口调用服务controller层

import com.hysoft.studyfeign.service.sysuserclient;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@requestmapping("feign")
public class sysusercontroller {

    @autowired
    private sysuserclient sysuserclient;

    @postmapping("getuserid")
    public void getuserid(string userid){
        this.sysuserclient.getuserbyid(userid);
    }

}

2.3、服务接口调用service层

feign的客户端需要使用@feignclient注解进行表示,这样扫描时才知道这是一个feign客户端。@feignclient最常用的就两个属性,一个name,用于给客户端定义一个唯一的名称,另一个就是url,用于定义该客户端调用的远程地址。url中的内容,可以写在配置文件application.yml中,便于管理

@service
@feignclient(name = "feign-service",url = "${master-getuserbyid}")
public interface sysuserclient {

    @postmapping("/master/test")
    string getuserbyid(string id);

}

application.yml中的配置如下

server:
  port: 8081
master-getuserbyid: http://localhost:8080

3、服务接口提供者

对于接口提供者来说没有特别要求,和正常的接口开发一样

4、说明

需要说明的是,在接口调用方,可以继续拓展service层,书写service实现层,进一步进行拓展    

import org.springframework.stereotype.service;

@service
public class sysuserclientimpl implements sysuserclient{
    @override
    public string getuserbyid(string id) {
        return "";
    }
}

使用resttemplate调用

resttemplate中几个常用的方法:getforobject()、getforentity()、postforobject()、postforentity()。其中,getforobject() 和 getforentity() 方法可以用来发送 get 请求

1、引入依赖

  <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
  </dependency>

2、resttemplateconfig配置类

simpleclienthttprequestfactory类对应的http库是jdk自带的httpurlconnection,当然我们可以根据自身的需求使用其他的http库,例如httpcomponentsasyncclienthttprequestfactory

@configuration
public class resttemplateconfig {

    @bean
    public resttemplate resttemplate(clienthttprequestfactory factory){
        return new resttemplate(factory);
    }

    @bean
    public clienthttprequestfactory simpleclienthttprequestfactory(){
        simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory();
        factory.setreadtimeout(5000);//单位为ms
        factory.setconnecttimeout(5000);//单位为ms
        return factory;
    }
}

3、接口调用

@restcontroller
public class testresttemplate {
    @resource
    private resttemplate resttemplate;

    @getmapping(value = "/saveuser")
    public void saveuser(string userid) {
        string url = "http://127.0.0.1:8080/master/test";
        map map = new hashmap<>();
        map.put("userid", "hy001");
        string results = resttemplate.postforobject(url, map, string.class);
    }
  }

使用webclient调用

spring3.0引入了resttemplate,但是在后来的官方源码中介绍,resttemplate有可能在未来的版本中被弃用,所谓替代resttemplate,在spring5中引入了webclient作为异步的非阻塞、响应式的http客户端。

1、引入依赖

<dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-webflux</artifactid>
</dependency>

2、接口调用示例

public class testwebclient {
    @test
    public void doget() {
        string userid = "郭郭";
        string url = "http://127.0.0.1:8080/master/test/getsysuserbyid?userid={userid}";
        mono<string> mono = webclient
                //创建webclient实例
                .create()
                //方法调用,webclient中提供了多种方法
                .get()
                //请求url
                .uri(url, userid)
                //获取响应结果
                .retrieve()
                //将结果转换为指定类型
                .bodytomono(string.class);
        //返回最终结果:block是阻塞的/subscribe()非阻塞式获取响应结果
        system.out.println("响应结果:" + mono.block());
    }
    @test
    public void dopost() {
        map map = new hashmap<>();
        map.put("name", "郭郭");
        string requestbody = json.tojsonstring(map);
        string url = "http://127.0.0.1:8080/master/test/saveuser";
        mono<string> mono = webclient
                //创建webclient实例
                .create()
                //方法调用,webclient中提供了多种方法
                .post()
                //请求url
                .uri(url)
                //指定请求的content-type为json
                .contenttype(mediatype.application_json)
                //使用bodyvalue方法传递请求体
                .bodyvalue(requestbody)
                //获取响应结果
                .retrieve()
                //将结果转换为指定类型
                .bodytomono(string.class);
        //返回最终结果:block是阻塞的/subscribe()非阻塞式获取响应结果
        system.out.println("响应结果:" + mono.block());
    }
}

在上述dopost请求中,我们的请求接口入参是一个map,但是需要转换为json格式传递,这是因为webclient默认是使用json序列化的。

使用apache httpclient调用

public class testhttpclient {
    @test
    public void doget() throws ioexception {
        //步骤一:创建httpclient实例
        closeablehttpclient httpclient = httpclients.createdefault();
        //步骤二:创建http请求
        httpget httpget = new httpget("http://127.0.0.1:8094/masterdata/sysuser/getsysuserbyid?userid=郭郭");
        //步骤三:发送请求并获取响应数据
        closeablehttpresponse response = httpclient.execute(httpget);
        //步骤四:处理响应数据
        httpentity entity = response.getentity();
        string result = entityutils.tostring(entity);
        //步骤五:关闭httpclient和response
        response.close();
        httpclient.close();
    }
    @test
    public void dopost() throws ioexception {
        //步骤一:创建httpclient实例
        closeablehttpclient httpclient = httpclients.createdefault();
        //步骤二:创建http请求
        httppost httppost = new httppost("http://127.0.0.1:8094/masterdata/sysuser/saveuser");
        //步骤三:设置请求体数据,使用json格式
        map map = new hashmap<>();
        map.put("name", "郭郭");
        string requestbody = json.tojsonstring(map);
        stringentity stringentity = new stringentity(requestbody, "utf-8");
        stringentity.setcontenttype("application/json");
        httppost.setentity(stringentity);
        
        //步骤四:发送请求并获取响应数据
        closeablehttpresponse response = httpclient.execute(httppost);
        //步骤五:处理响应数据
        httpentity entity = response.getentity();
        string result = entityutils.tostring(entity);
        //步骤五:关闭httpclient和response
        response.close();
        httpclient.close();
    }
}

使用httpurlconnection调用

public class testhttpurlconnection {

    @test
    public void doget() throws ioexception {
        string userid = "郭郭";  // 参数值
        userid = urlencoder.encode(userid, "utf-8"); // 对参数值进行url编码
        //步骤一:创建url对象
        url url = new url("http://127.0.0.1:8094/masterdata/sysuser/getsysuserbyid?userid=" + userid);
        //步骤二:打开连接
        httpurlconnection conn = (httpurlconnection) url.openconnection();
        //步骤三:设置请求方式
        conn.setrequestmethod("get");
        //步骤四:读取响应内容
        bufferedreader reader = new bufferedreader(new inputstreamreader(conn.getinputstream()));
        stringbuilder sb = new stringbuilder();
        string line;
        while ((line = reader.readline()) != null) {
            sb.append(line);
        }
        reader.close();
        system.out.println(sb.tostring());
    } 
    @test
    public void dopost() throws ioexception {
        //创建url对象
        url url = new url("http://127.0.0.1:8094/masterdata/sysuser/saveuser");
        //打开连接
        httpurlconnection conn = (httpurlconnection) url.openconnection();
        //设置请求方式
        conn.setrequestmethod("post");
        // 设置请求头
        conn.setrequestproperty("content-type", "application/json");
        //启用输出流
        conn.setdooutput(true);
        //设置请求体数据
        map map = new hashmap<>();
        map.put("name", "郭郭");
        string requestbody = json.tojsonstring(map);
        //发送请求体数据
        try (dataoutputstream outputstream = new dataoutputstream(conn.getoutputstream())) {
            outputstream.write(requestbody.getbytes(standardcharsets.utf_8));
        }

        //读取响应内容
        bufferedreader reader = new bufferedreader(new inputstreamreader(conn.getinputstream()));
        stringbuilder sb = new stringbuilder();
        string line;
        while ((line = reader.readline()) != null) {
            sb.append(line);
        }
        reader.close();
        system.out.println(sb.tostring());
    } 
  }

使用okhttp调用

1、引入依赖

<!--okhttp依赖-->
  <dependency>
    <groupid>com.squareup.okhttp3</groupid>
    <artifactid>okhttp</artifactid>
    <version>4.0.0</version>
  </dependency>

2、示例代码

public class testokhttp {

    @test
    public void doget() throws ioexception {
        okhttpclient client = new okhttpclient();
        string url = "http://127.0.0.1:8080/master/test/getsysuserbyid?userid=郭郭";
        request request = new request.builder().url(url).build();
        try (response response = client.newcall(request).execute()) {
            responsebody body = response.body();
            system.out.println(body.string());
        }
    }

    @test
    public void dopost() throws ioexception{
        okhttpclient client = new okhttpclient();
        string url = "http://127.0.0.1:8080/master/test/saveuser";
        mediatype mediatype = mediatype.get("application/json; charset=utf-8");
        //requestbody请求入参
        map map = new hashmap<>();
        map.put("name", "admin");
        requestbody requestbody = requestbody.create(mediatype, json.tojsonstring(map));
        request request = new request.builder()
                .url(url)
                .post(requestbody)
                .build();
        try (response response = client.newcall(request).execute()) {
            responsebody body = response.body();
            system.out.println(body.string());
        }
    }
}

使用asynchttpclient调用

1、引入依赖

<dependency>
      <groupid>org.asynchttpclient</groupid>
      <artifactid>async-http-client</artifactid>
      <version>2.12.3</version>
</dependency>

2、示例代码

public class testasynchttpclient {
    @test
    public void doget() throws ioexception {
        try (asynchttpclient client = new defaultasynchttpclient();) {
            boundrequestbuilder requestbuilder = client.prepareget("http://127.0.0.1:8080/master/test/getsysuserbyid?userid=hy001");
            completablefuture<string> future = requestbuilder.execute()
                    .tocompletablefuture()
                    .thenapply(response::getresponsebody);
            //使用join等待响应完成
            string responsebody = future.join();
            system.out.println(responsebody);
        }
    }
    @test
    public void dopost() throws ioexception {
        try (asynchttpclient client = new defaultasynchttpclient();) {
            boundrequestbuilder requestbuilder = client.preparepost("http://127.0.0.1:8094/8080/master/test/saveuser");
            //requestbody请求入参
            map map = new hashmap<>();
            map.put("name", "admin");
            string requestbody = json.tojsonstring(map);
            requestbuilder.addheader("content-type", "application/json");
            requestbuilder.setbody(requestbody);
            completablefuture<string> future = requestbuilder.execute()
                    .tocompletablefuture()
                    .thenapply(response::getresponsebody);
            //使用join等待响应完成
            string responsebody = future.join();
            system.out.println(responsebody);
        }
    }
  }

到此这篇关于springboot调用外部接口的几种方式的文章就介绍到这了,更多相关springboot调用外部接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com