springboot接口远程调用(URL,feign)

方式一:URL

package com.xhkjedu.controller.classin;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.utils.MD5;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import com.xhkjedu.vo.classin.CResultVo;
import com.xhkjedu.vo.classin.ClassInVo;
import com.xhkjedu.vo.classin.ErrorInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author ywx
 * @className ClassInController
 * @description
 * @date 2021/1/15 13:57
 **/
@RestController
@RequestMapping("/classin")
@Slf4j
public class ClassInController {

    @PostMapping("/send_post")
    public ResultVo sendPost(@RequestBody ClassInVo classin) {
        String sid = "";
        String secret="";
        if (N_Utils.isEmpty(sid) || N_Utils.isEmpty(secret)){
            return new ResultVo(1,"该学校未开通直播权限");
        }
        String url = classin.getUrl();
        String param = classin.getParam();
        MD5 md5 = new MD5();
        String sign = classin.getSign();
        String sign2 = md5.getJsMD5(param);
        if (!sign.equals(sign2)){
            return new ResultVo(1,"签名校验失败");
        }
        int timestamp = N_Utils.getSecondTimestamp();
        String safeKey = md5.getJsMD5(secret+timestamp);
        StringBuilder sb = new StringBuilder();
        sb.append(param);
        sb.append("&SID=").append(sid);
        sb.append("&safeKey=").append(safeKey);
        sb.append("&timeStamp=").append(timestamp);
        String result = sendPost(url, sb.toString());
        CResultVo vo = JSON.parseObject(result, CResultVo.class);
        ErrorInfoVo errorInfo = vo.getError_info();
        if (errorInfo.getErrno() == 1) {
            return new ResultVo(0,"调用classin接口成功",result);
        } else {
            return new ResultVo(1,errorInfo.getError());
        }
    }

    //向指定 URL 发送POST方法的请求
    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //json形式参数
//            conn.setRequestProperty("accept", "application/json");
//            conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");

            //form表单
            conn.setRequestProperty("accept", "application/x-www-form-urlencoded");

            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置请求编码格式
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            // 文件流编码设置
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常!" + e.getMessage());
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("关闭输入输出流异常", ex.getMessage());
            }
        }
        return result;
    }
}

方式二:feign

1、pom.xml引入feign包

<!--远程调用-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

2、FeignClient

package com.xhkjedu.config;

import com.xhkjedu.vo.ResultVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Component
@FeignClient(url = "${ssoURL}", name = "ssoURL")
public interface FeignURL {

    //去认证服务器 删除认证系统的用户信息
    @RequestMapping(value = "/school/ssoDeleteUser", method = RequestMethod.POST)
    public ResultVo ssoDeleteUser(@RequestParam(value = "userid") Integer userid);

    //去认证服务器更新用户信息
    @RequestMapping(value = "/school/ssoupdateUser", method = RequestMethod.POST)
    public ResultVo ssoUpdateUser(@RequestParam(value = "object_string") String object_string);
}

3、Controller

package com.xhkjedu.controller.system;

import com.xhkjedu.config.FeignURL;
import com.xhkjedu.service.system.UserService;
import com.xhkjedu.vo.ResultVo;
import com.xhkjedu.vo.system.TUserBean;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private FeignURL feginssoURL;


    //删除用户
    @RequestMapping(value = "/deleteTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultVo deleteTeacher(Integer userid) {
        ResultVo result = new ResultVo();
        result.setCode(1);
        try {
            ResultVo vo = feginssoURL.ssoDeleteUser(userid);
            //删除完毕
            if (vo.getCode() == 0) {
                userService.delete(userid);
                result.setCode(0);
            } else {
                throw new Exception(vo.getMsg());
            }
        } catch (Exception e) {
            log.error("删除用户出错:" + e.getMessage());
            result.setMsg("删除用户出错:" + e.getMessage());
        }
        return result;
    }

    //用户信息修改
    @RequestMapping("/modifyTeacher")
    public ResultVo modifyTeacher(TUserBean user, Integer sssourcesid) {
        ResultVo result = new ResultVo();
        ObjectMapper mapper = new ObjectMapper();
        result.setCode(1);
        try {
            TUserBean suser = user;
            suser.setUserid(sssourcesid);
            String object_string = mapper.writeValueAsString(suser);
            ResultVo vo = feginssoURL.ssoUpdateUser(object_string);
            //更新完毕
            if (vo.getCode() == 0) {
                userService.update(user);
                result.setCode(0);
            } else {
                throw new Exception(vo.getMsg());
            }
        } catch (Exception e) {
            log.error("修改用户信息出错" + e.getMessage());
            result.setMsg("修改用户信息出错:" + e.getMessage());
        }
        return result;
    }

}

4、启动类加上@EnableFeignClients

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: springboot feign 的调用例子可以这样:1. 创建一个FeignClient接口,定义要调用的远程接口:@FeignClient("springboot-service") public interface SpringbootService { @RequestMapping("/hello") String hello(); }2. 在需要调用的地方注入FeignClient接口:@Autowired private SpringbootService springbootService;3. 调用远程接口:String result = springbootService.hello(); ### 回答2: Spring Boot Feign 是一种用于简化 RESTful 服务调用的声明式 HTTP 客户端。下面是一个简单的基于 Spring Boot Feign 的调用示例。 首先,需要在项目的 pom.xml 文件中添加Feign和Spring Cloud 相关的依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 然后,在主启动类上添加 `@EnableFeignClients` 注解以启用 Feign 客户端: ```java @SpringBootApplication @EnableFeignClients public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 接下来,创建一个 Feign 客户端接口,并使用 `@FeignClient` 注解指定要调用的远程服务: ```java @FeignClient(name = "remote-service") public interface RemoteServiceClient { @GetMapping("/api/user/{id}") UserDTO getUserById(@PathVariable Long id); } ``` 在上述示例中,我们创建了一个名为 `RemoteServiceClient` 的 Feign 客户端接口,并指定其调用的远程服务名称为 "remote-service"。接口中的 `getUserById` 方法用于调用 "remote-service" 服务的 "/api/user/{id}" 接口,并接收一个路径变量 id,返回类型为 UserDTO。 最后,在需要调用远程服务的地方注入 `RemoteServiceClient` 客户端接口,并使用它进行调用: ```java @RestController public class UserController { @Autowired private RemoteServiceClient remoteServiceClient; @GetMapping("/user/{id}") public UserDTO getUserById(@PathVariable Long id) { return remoteServiceClient.getUserById(id); } } ``` 在上述示例中,我们在 UserController 中注入了 `RemoteServiceClient` 客户端接口,并使用它调用远程服务的 getUserById 方法,返回结果作为该接口的返回值。 通过以上步骤,就可以完成一个简单的 Spring Boot Feign 调用示例。注意,还需要配置远程服务的地址和端口等相关配置。 ### 回答3: Spring Boot Feign是一个基于HTTP请求的声明式Web Service客户端。它使用注解方式声明和配置对其他服务的调用,并且提供了一些便捷的功能,使得与其他服务的通信更加简单高效。下面是一个关于使用Spring Boot Feign的调用例子。 首先,我们需要在项目的pom.xml文件中添加Feign的依赖。 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.3.RELEASE</version> </dependency> ``` 然后,在启动类上添加@EnableFeignClients注解以启动Feign功能。 ```java @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 接下来,我们创建一个Feign接口,并使用@FeignClient注解指定要调用的服务的名称和URL。 ```java @FeignClient(name = "example-service", url = "http://localhost:8080") public interface ExampleFeignClient { @GetMapping("/example") String getExample(); } ``` 在上面的例子中,我们声明了一个名为ExampleFeignClient的Feign接口,它会调用一个名为example-service的服务,并且该服务的URL是http://localhost:8080。 最后,我们可以在其他组件中使用ExampleFeignClient接口来进行调用。 ```java @RestController public class ExampleController { private final ExampleFeignClient exampleFeignClient; public ExampleController(ExampleFeignClient exampleFeignClient) { this.exampleFeignClient = exampleFeignClient; } @GetMapping("/example-feign") public String invokeExampleService() { return exampleFeignClient.getExample(); } } ``` 上面的例子中,我们在ExampleController中注入了ExampleFeignClient接口,在调用invokeExampleService方法时,实际上是调用了ExampleFeignClient接口中的getExample方法。 这就是一个简单的Spring Boot Feign调用例子。使用Feign能够简化微服务之间的通信,提高开发效率。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值