java调用一个外部url_Spring Boot :访问外部接口

本文介绍了在Spring Boot项目中调用外部URL接口的三种方法:1) 使用原生Http请求,2) 通过Feign客户端,3) 利用RestTemplate。详细阐述了每种方法的实现步骤和示例代码。
摘要由CSDN通过智能技术生成

原标题:Spring Boot :访问外部接口

在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求, 比如调用外部的地图API或者天气API。

方案一: 采用原生的Http请求

在代码中采用原生的http请求,代码参考如下:

@RequestMapping( "/doPostGetJson")

publicString doPostGetJson( ) throws ParseException{

//此处将要发送的数据转换为json格式字符串

String jsonText = "{id: 1}";

JSONObject json = (JSONObject) JSONObject.parse(jsonText);

JSONObject sr = this.doPost(json);

System. out.println( "返回参数: "+ sr);

returnsr.toString;

}

publicstaticJSONObject doPost( JSONObject date){

HttpClient client = HttpClients.createDefault;

// 要调用的接口方法

String url = "http://192.168.1.101:8080/getJson";

HttpPost post = newHttpPost(url);

JSONObject jsonObject = null;

try{

StringEntity s = newStringEntity(date.toString);

s.setContentEncoding( "UTF-8");

s.setContentType( "application/json");

post.setEntity(s);

post.addHeader( "content-type", "text/xml");

HttpResponse res = client.execute(post);

String response1 = EntityUtils.toString(res.getEntity);

System. out.println(response1);

if(res.getStatusLine.getStatusCode == HttpStatus.SC_OK) {

String result = EntityUtils.toString(res.getEntity); // 返回json格式:

jsonObject = JSONObject.parseObject(result);

}

} catch(Exception e) {

thrownewRuntimeException(e);

}

returnjsonObject;

}

方案二: 采用Feign进行消费

1、在maven项目中添加依赖

< dependency>

< groupId>org.springframework.cloud groupId>

< artifactId>spring-cloud-starter-feign artifactId>

< version>1.2.2.RELEASE version>

dependency>

2、编写接口,放置在service层

这里的decisionEngine.url 是配置在properties中的 是ip地址和端口号decisionEngine.url=http://10.2.1.148:3333/decision/person 是接口名字

@FeignClient(url = " ${decisionEngine.url}",name= "engine")

publicinterfaceDecisionEngineService{

@RequestMapping(value= "/decision/person",method= RequestMethod.POST)

publicJSONObject getEngineMesasge( @RequestParam( "uid")String uid, @RequestParam( "productCode")String productCode);

}

3、在Java的启动类上加上@EnableFeignClients

@EnableFeignClients//参见此处

@EnableDiscoveryClient

@SpringBootApplication

@EnableResourceServer

publicclassApplicationimplementsCommandLineRunner{

privatestaticfinalLogger LOGGER = LoggerFactory.getLogger(Application.class);

@Autowired

privateAppMetricsExporter appMetricsExporter;

@Autowired

privateAddMonitorUnitService addMonitorUnitService;

publicstaticvoidmain(String[] args){

newSpringApplicationBuilder(Application.class).web( true).run(args);

}

}

4、在代码中调用接口即可

@Autowired

privateDecisionEngineService decisionEngineService ;

// ...

decisionEngineService.getEngineMesasge( "uid", "productCode");

方案三: 采用RestTemplate方法

在Spring-Boot开发中,RestTemplate同样提供了对外访问的接口API,这里主要介绍Get和Post方法的使用。Get请求提供了两种方式的接口getForObject 和 getForEntity,getForEntity提供如下三种方法的实现。

Get请求之——getForEntity(Stringurl,Class responseType,Object…urlVariables)

该方法提供了三个参数,其中url为请求的地址,responseType为请求响应body的包装类型,urlVariables为url中的参数绑定,该方法的参考调用如下:

// http://USER-SERVICE/user?name={name)

RestTemplate restTemplate= newRestTemplate;

Map< String, String> params= newHashMap<>;

params.put( "name", "dada"); //

ResponseEntity< String> responseEntity=restTemplate.getForEntity( "http://USERSERVICE/user?name={name}", String. class,params);

Get请求之——getForEntity(URI url,Class responseType)

该方法使用URI对象来替代之前的url和urlVariables参数来指定访问地址和参数绑定。URI是JDK java.net包下的一个类,表示一个统一资源标识符(Uniform Resource Identifier)引用。参考如下:

RestTemplate restTemplate= newRestTemplate;

UriComponents uriComponents=UriComponentsBuilder.fromUriString( "http://USER-SERVICE/user?name={name}")

.build

.expand( "dodo")

.encode;

URI uri=uriComponents.toUri;

ResponseEntity< String> responseEntity=restTemplate.getForEntity(uri, String. class).getBody;

Get请求之——getForObject

getForObject方法可以理解为对getForEntity的进一步封装,它通过HttpMessageConverterExtractor对HTTP的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容。getForObject方法有如下:

getForObject( Stringurl, ClassresponseType, Object...urlVariables)

getForObject( Stringurl, ClassresponseType,Map urlVariables)

getForObject(URI url, ClassresponseType)

Post 请求

Post请求提供有三种方法,postForEntity、postForObject和postForLocation。其中每种方法都存在三种方法,postForEntity方法使用如下:

RestTemplate restTemplate= newRestTemplate;

User user=newUser( "didi", 30);

ResponseEntity< String> responseEntity=restTemplate.postForEntity( "http://USER-SERVICE/user",user, String. class); //提交的body内容为user对象,请求的返回的body类型为String

Stringbody=responseEntity.getBody;

postForEntity存在如下三种方法的重载

postForEntity( Stringurl, Objectrequest, ClassresponseType, Object... uriVariables)

postForEntity( Stringurl, Objectrequest, ClassresponseType,Map uriVariables)

postForEntity(URI url, Objectrequest, ClassresponseType)

postForEntity中的其它参数和getForEntity的参数大体相同在此不做介绍。

参考文章

pdai

http://dwz.win/tYx返回搜狐,查看更多

责任编辑:

Spring Boot可以通过RestTemplate或Feign Client调用外部接口。 1. RestTemplate RestTemplate是Spring提供的用于调用RESTful服务的客户端。它可以发送HTTP请求并处理响应。使用RestTemplate需要在Spring Boot项目中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> ``` 使用RestTemplate发送GET请求: ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/api/users"; String response = restTemplate.getForObject(url, String.class); ``` 使用RestTemplate发送POST请求: ```java RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/api/users"; User user = new User("John", "Doe"); User response = restTemplate.postForObject(url, user, User.class); ``` 2. Feign Client Feign是一个声明式、模板化的HTTP客户端,可以与Spring Boot无缝集成。使用Feign需要在Spring Boot项目中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 定义Feign客户端接口: ```java @FeignClient(name = "user-service") public interface UserServiceClient { @GetMapping("/api/users/{id}") User getUser(@PathVariable("id") Long id); @PostMapping("/api/users") User createUser(@RequestBody User user); } ``` 使用Feign客户端调用外部接口: ```java @Autowired private UserServiceClient userServiceClient; public User getUser(Long id) { return userServiceClient.getUser(id); } public User createUser(User user) { return userServiceClient.createUser(user); } ``` 以上是Spring Boot调用外部接口的两种方式,根据实际情况选择合适的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值