SpringBoot中调用第三方接口的三种方式

x33g5p2x  于2022-05-31 转载在 Spring  
字(8.8k)|赞(0)|评价(0)|浏览(766)

使用SpringBoot跨系统调用接口的方案

一、简介

项目开发中存在系统之间互调问题,又不想用dubbo,这里提供几种SpringBoot方案:

1、使用Feign进行消费(推荐)

2、使用原始httpClient请求

3、使用RestTemplate方法

二、方案

方案一:使用Feign进行消费(推荐)

1、在maven中添加依赖

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

2、启动类上加上@EnableFeignClients

@EnableHystrix
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.aaa.aurora"})
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = "com.aaa.aurora")
@ImportResource(locations= {"classpath:spring.xml","spring-security.xml"})
@MapperScan("com.aaa.aurora.mapper")
public class AuroraWebApplication {

 public static void main(String[] args) {
   SpringApplication.run(AuroraWebApplication.class, args);
  }
}

3、编写service接口

@FeignClient(url = "${pangu.url}",name = "panguUrl")
public interface PanGuService {
 
 @RequestMapping(value = "/pangu/restful/check",method = RequestMethod.POST)
 JSONObject check(@RequestParam(name="queryEngine") String queryEngine, @RequestParam(name="querySql") String querySql, @RequestParam(name="jobNo") String jobNo);

}

其中:pangu.url是配置在application.properties中的ip及端口

pangu.url = 192.168.1.3:8080

/pangu/restful/check是要调的接口名

4、代码中调用

@Autowired
private PanGuService panGuService;
JSONObject jsonObject = null;
try {
  jsonObject = panGuService.auroraPriviledge(PRESTO_DRIVER, query.get("sql"), user.getWorkNo());
} catch (Exception e) {
 throw new Exception("请求系统异常");
}
if (PANGU_FAIL.equals(jsonObject.get("code"))) {
 LOG.info(jsonObject.get("msg").toString());
 throw new BusinessException(jsonObject.get("msg").toString());
}

方案二:使用原始httpClient请求

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接。
@Autowired
private PanGuService panGuService;
JSONObject jsonObject = null;
try {
  jsonObject = panGuService.auroraPriviledge(PRESTO_DRIVER, query.get("sql"), user.getWorkNo());
} catch (Exception e) {
 throw new Exception("请求系统异常");
}
if (PANGU_FAIL.equals(jsonObject.get("code"))) {
 LOG.info(jsonObject.get("msg").toString());
 throw new BusinessException(jsonObject.get("msg").toString());
}

方案三:使用RestTemplate方法

1.get请求:getForObject(…)和getForEntity(…)两个方法,区别在于前者直接返回预期的对象,即返回体中的body对象,后者返回的是ResponseEntity封装类,里面包含了HTTP请求的头信息。

2.post请求:与get请求类似,只是多一个request参数,request对象会作为httpEntity进行处理。

package com.yyy.aurora;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class TestRest {

 public static void main(String[] args) {
  RestTemplate restTemplate = new RestTemplate();
  //get请求
  //方法一:getForEntity(String url, Class<T> responseType, Object... uriVariables),没有参数
  String url = "https://restapi.amap.com/v3/ip?key=075b6eddd825148a674dfa8a8558ac62"
  ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
  System.out.println(forEntity);
  // <200,{"status":"1","info":"OK","infocode":"10000","province":"上海市","city":"上海
  市","adcode":"310000","rectangle":"120.8397067,30.77980118;122.1137989,31.66889673"},{Server=[Tengine], Date=[Sat, 18 Apr 2020 02:47:38 GMT], Content-
  Type=[application/json;charset=UTF-8], Content-Length=[167], Connection=[close], X-Powered-By=[ring/1.0.0], gsid=
  [011130051098158717805837600019751129378], sc=[0.071], Access-Control-Allow-Origin=[*], Access-Control-Allow-Methods=[*], Access-Control-Allow-
  Headers=[DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,key,x-biz,x-
  info,platinfo,encr,enginever,gzipped,poiid]}>

  

  String s = restTemplate.getForObject(url, String.class);
  System.out.println(s);
  // {"province":"上海市","city":"上海市","adcode":"310000","infocode":"10000","rectangle":"120.8397067,30.77980118;122.1137989,31.66889673","status":"1","info":"OK"}

  //方法一:getForEntity(String url, Class<T> responseType, Object... uriVariables),url中用占位符,传入参数
  //该方法提供了三个参数,其中var1为请求的地址(即url),var2为请求响应body的包装类型,var3为url中的参数绑定
  url = "https://restapi.amap.com/v3/ip?key={?}";
  forEntity = restTemplate.getForEntity(url, String.class, "075b6eddd825148a674dfa8a8558ac62");
  
  //方法二:getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables),map传参
  url = "https://restapi.amap.com/v3/ip?key={key}";
  Map<String, Object> map = new HashMap<>();
  map.put("key", "075b6eddd825148a674dfa8a8558ac62");
  forEntity = restTemplate.getForEntity(url, String.class, map);

  //方法三:getForEntity(URI url, Class<T> responseType),uri传参
  URI uri = URI.create("https://restapi.amap.com/v3/ip?key=075b6eddd825148a674dfa8a8558ac62");
  forEntity = restTemplate.getForEntity(uri, String.class);
  //post请求,与get请求类型,只是多一个必填request对象
  //postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
  forEntity = restTemplate.postForEntity(url, null, String.class, "075b6eddd825148a674dfa8a8558ac62");
  s = restTemplate.postForObject(url, null, String.class, "075b6eddd825148a674dfa8a8558ac62");
 }
}

补充:SpringBoot关于系统之间的远程互相调用

1、SpringBoot关于系统之间的远程互相调用

可以采用RestTemplate方式发起Rest Http调用,提供有get、post等方式。

1、1远程工具类

此处使用Post方式,参考下面封装的HttpClient类 1.1

/**
 * Desc: 远程连接工具类
 */
@Service
public class HttpClient {

 /**
 * 根据远程地址发起访问-参数类型为form表单
 * @param url 远程地址
 * @param method 远程方法
 * @param params  方法参数
 * @return
 */
 public Object client(String url,HttpMethod method,MultiValueMap<String,String> params){
  RestTemplate restTemplate = new RestTemplate();
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Type", "application/x-www-form-urlencoded");
  HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);
  ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,httpEntity,String.class);
  String body = responseEntity.getBody();
  JSONObject jsonObject = JSONObject.parseObject(body);
  return jsonObject.get("data");
 }

 /**
 * 根据远程地址发起访问-参数类型为JSON
 * @param url 远程地址
 * @param method 远程方法
 * @aram params  方法参数
 * @eturn
 */
 public Object clientJson(String url,HttpMethod method,Map<String,Object> params){
  RestTemplate restTemplate = new RestTemplate();
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  cn.hutool.json.JSONObject jsonObject = JSONUtil.parseFromMap(params);
  HttpEntity<cn.hutool.json.JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
  ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,httpEntity,String.class);
  String body = responseEntity.getBody();
  JSONObject jsonObjectResult = JSONObject.parseObject(body);
  return jsonObjectResult.get("data");
 }
}

1、2远程参数说明

工具类中提供了远程过程中传递参数的两种格式:

其中 headers.add(“Content-Type”, “application/x-www-form-urlencoded”) 为form表单格式,支持键值对数据传输;

当参数类型为form表单时,数据需要封装成MultiValueMap<String,String>格式,前台使用controller接受时,可以直接使用 MultiValueMap 变量接收,代码如下

接受参数为form对象

/**
 * 保存分组策略对象
 * @param
 * @return
 */
@RequestMapping(value = "/saveDocGroupPolicy",method = RequestMethod.POST)
public ApiResult saveGroupPolicy(@RequestParam MultiValueMap<String,String> paramMap,@Valid GroupStrategyIO groupStrategyIO){
 Integer userId = ShiroUtil.getExamUserId();
 List<String> userList = new ArrayList<>();
 userList.add(userId+"");
 paramMap.put("userId",userList);
 Object jsonObject = httpClient.client(ExamConfigConstants.url+"/exam/configPolicy/saveDocGroupPolicy", HttpMethod.POST, paramMap);
 return ApiResult.success(jsonObject);
}
headers.setContentType(MediaType.APPLICATION_JSON_UTF8)

接收参数为复杂json串
为json数据格式

当参数为json格式时,远程服务器接受参数需加上注解@RequestBody,对于复杂参数可以使用对象接受,将对象转为Map,对数据进行加工,再将map转化为JSONObject

/**
 * 保存试卷策略
 * @param paperStrategyIO 试卷策略对象
 * @return
 */

@RequestMapping(value = "/savePaperConfig")
public ApiResult savePaperConfig(@RequestBody PaperStrategyIO paperStrategyIO){
 Map<String, Object> paramMap = BeanUtil.beanToMap(paperStrategyIO);
 Integer userId = ShiroUtil.getExamUserId();
 paramMap.put("userId",userId);
 Object jsonObject = httpClient.clientJson(ExamConfigConstants.url+"/exam/paper/savePaperConfigWithMap", HttpMethod.POST, paramMap);
 return ApiResult.success(jsonObject);
}

2、后记

关于RestTemplate还有很多可调用的API,可以查看官方网站了解

REST in Spring 3: RestTemplate

相关文章