Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign
This article demonstrates three practical approaches for invoking external services in a Spring Boot application—using a raw HttpClient, the RestTemplate utility, and the Feign declarative client—complete with code examples, configuration steps, and tips for handling headers and tokens.
Spring Boot inherits Spring's strengths while simplifying configuration, and many projects need to call external URLs or third‑party services. This guide presents three methods to achieve that without Dubbo.
1. Method One: Raw HttpClient Request
Use Apache HttpClient to build and send a POST request, set JSON payload, add the Authorization header, and parse the JSON response.
/*
* @description get方式获取入参,插入数据并发起流程
* @author lyx
* @date 2022/8/24 16:05
* @params documentId
* @return String
*/
@RequestMapping("/submit/{documentId}")
public String submit1(@PathVariable String documentId) throws ParseException {
Map
map = task2Service.getMap(documentId);
String jsonStr = JSON.toJSONString(map, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
JSONObject jsonObject = JSON.parseObject(jsonStr);
JSONObject sr = task2Service.doPost(jsonObject);
return sr.toString();
}
/*
* @description 使用原生httpClient调用外部接口
* @author lyx
* @date 2022/8/24 16:08
* @params date
* @return JSONObject
*/
public static JSONObject doPost(JSONObject date) {
String assessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...";
CloseableHttpClient client = HttpClients.createDefault();
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
HttpPost post = new HttpPost(url);
StringEntity s = new StringEntity(date.toString());
s.setContentType("application/json");
s.setContentEncoding("UTF-8");
post.setEntity(s);
post.addHeader("Authorization", "Bearer " + assessToken);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());
return JSONObject.parseObject(result);
}
throw new RuntimeException("Request failed");
}2. Method Two: RestTemplate
RestTemplate provides convenient getForObject , getForEntity , postForEntity , postForObject , and postForLocation methods. Examples show how to build URIs, pass parameters, and retrieve responses.
RestTemplate restTemplate = new RestTemplate();
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri = uriComponents.toUri();
ResponseEntity
response = restTemplate.getForEntity(uri, String.class);3. Method Three: Feign Client
Add the Feign starter dependency, enable Feign with @EnableFeignClients , and define a Feign interface annotated with @FeignClient . Include a custom RequestInterceptor to inject tokens into request headers.
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
}
}
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
@RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}Finally, a controller can autowire the Feign client and expose an endpoint that forwards the request to the external service.
@RestController
public class DemoController {
@Autowired
FeignService2 feignService2;
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}
}Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.