【SpringBoot请求外部接口的方法】

Java请求外部接口的两种方法

  • SpringBoot请求外部接口
    • 环境准备
    • 请求外部接口

SpringBoot请求外部接口

环境准备

引入依赖:

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
     <version>2.1.1.RELEASE</version>
 </dependency>

在启动上加入@EnableFeignClients

@SpringBootApplication(exclude = {MybatisDataSourceAutoConfiguration.class, SecurityAutoConfiguration.class})
@ComponentScan(nameGenerator = UniqueNameGenerator.class)
@EnableFeignClients
@EnableAsync
public class GunsApplication {

    private final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);

    public static void main(String[] args) {
        try {
            SpringApplication.run(GunsApplication.class, args);
        }catch (Exception e){
            e.printStackTrace();
        }
        logger.info(GunsApplication.class.getSimpleName() + " is success!");
    }
}

请求外部接口

@Controller
@RequestMapping("/frozen")
public class FrozenProductController extends BaseController {

    @Autowired
    private OpenController openController;

    @Autowired
    private PassageGoodsService passageGoodsService;
    @Autowired
    private ContentBateApi contentBateApi;
    /**
     * 新增接口
     *
     * @author px
     * @Date 2022-10-20
     */
    @PostMapping("/update")
    @ResponseBody
    public ResponseData update(String bns) {
        String token = ".....";

        // 将所有的bn转化成list
        Arrays.stream(bns.split(",")).distinct().forEach(bn -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("bn", bn);
            jsonObject.put("status", 1);
            jsonObject.put("newBn", "");
            jsonObject.put("reason", "集团停用编码");

            contentBateApi.updateState(token, 6, jsonObject.toJSONString());
        });
        return ResponseData.success();
    }
 }
@FeignClient(name = "ContentBateApi", url = "${beta.url}")
public interface ContentBateApi {
    /**
     * 推送冻结商品
     *
     * @return
     */
    @PostMapping(value = "/updateState", consumes = "application/json;charset=UTF-8")
    @ResponseBody
    ResponseData updateState(@RequestHeader("token") String token,
                             @RequestParam(value = "type") Integer type,
                             @RequestParam(value = "data") String data);
}

上面使用还需要带着token传送,当使用configuration = FeignMroConfig.class后就可以不用带上@RequestHeader(“token”) String token。当两个都存在的时候会用并且两个token的值不相同的时候出送过去的值将会是最开始的值,而不是用@RequestHeader(“token”) 所放入的值。

@FeignClient(name = "ContentBateApi", url = "${beta.url}",configuration = FeignMroConfig.class)
public interface ContentBateApi {
    /**
     * 推送冻结商品
     *
     * @return
     */
    @PostMapping(value = "/updateState", consumes = "application/json;charset=UTF-8")
    @ResponseBody
    ResponseData updateState(@RequestParam(value = "type") Integer type,
                             @RequestParam(value = "data") String data);
}

你可能感兴趣的:(java,spring,boot,java,spring,cloud)