Using Spring Boot to Call External APIs: HttpClient, RestTemplate, and Feign
This article explains how to invoke external services from a Spring Boot application using three approaches—raw HttpClient, Spring's RestTemplate, and Feign client—providing detailed code examples, configuration steps, and tips for handling headers and tokens.
1. Introduction
Spring Boot inherits the excellent features of the Spring framework and further simplifies application setup by reducing configuration. In Spring Boot projects, modules often need to call external interfaces or URLs, such as during apaas development where APIs like submit must be wrapped.
2. Method 1: Raw HttpClient
The following controller method receives a documentId , converts task data to JSON, and calls an external service via a custom doPost method that uses CloseableHttpClient , sets the Authorization Bearer token header, and returns 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 {
//此处将要发送的数据转换为json格式字符串
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();
}The doPost implementation creates an HttpPost request, adds JSON payload and token header, executes the request, and parses the JSON response.
/*
* @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);
JSONObject jsonObject = null;
try {
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());
jsonObject = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}3. Method 2: RestTemplate
Spring's RestTemplate also provides convenient API calls. For GET requests, getForEntity and getForObject have several overloads. The example below builds a URI with UriComponentsBuilder and retrieves the response body.
// getForEntity(URI url, Class responseType)
RestTemplate restTemplate = new RestTemplate();
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri = uriComponents.toUri();
ResponseEntity
responseEntity = restTemplate.getForEntity(uri, String.class);
String body = responseEntity.getBody();For POST requests, postForEntity , postForObject and postForLocation are available. The following snippet demonstrates postForEntity with a JSON payload.
/*
* @description post方式获取入参,插入数据并发起流程
* @author lyx
* @date 2022/8/24 16:07
*/
@PostMapping("/submit2")
public Object insertFinanceCompensation(@RequestBody JSONObject jsonObject) {
String documentId = jsonObject.get("documentId").toString();
return task2Service.submit(documentId);
}4. Method 3: Feign Client
Feign simplifies HTTP calls by declaring Java interfaces. Add the spring-cloud-starter-feign dependency, enable Feign with @EnableFeignClients , and define a Feign interface with request mappings.
org.springframework.cloud
spring-cloud-starter-feign
1.2.2.RELEASEApplication entry point:
@SpringBootApplication
@EnableFeignClients
@ComponentScan(basePackages = {"com.definesys.mpaas", "com.xdap.*"})
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}Feign service definition (example with token header interceptor):
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
@RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}Interceptor to add token header:
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
}
}Controller that uses the Feign client:
@Autowired
FeignService2 feignService2;
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}The article also includes a disclaimer and promotional material unrelated to the technical content.
IT Architects Alliance
Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.
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.