Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign
This article demonstrates three approaches for invoking external services in Spring Boot applications—using raw HttpClient, the RestTemplate utility, and Feign clients—providing code samples, configuration steps, and tips for handling headers and tokens.
Spring Boot simplifies Java backend development, but many scenarios require calling external HTTP interfaces. This guide presents three practical methods to achieve that: using the low‑level HttpClient , the higher‑level RestTemplate , and the declarative Feign client.
1. Using raw HttpClient
@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();
}
public static JSONObject doPost(JSONObject date) {
String assessToken = "
";
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. Using RestTemplate
RestTemplate offers convenient methods such as getForEntity , getForObject , and postForEntity . Example usages:
// GET with URI
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);
// GET with URL variables
Map
params = new HashMap<>();
params.put("name", "dada");
ResponseEntity
response2 = restTemplate.getForEntity("http://USER-SERVICE/user?name={name}", String.class, params);
// POST example
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer
");
headers.setContentType(MediaType.APPLICATION_JSON);
Map
map = getMap(documentId);
HttpEntity
entity = new HttpEntity<>(map, headers);
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity
postResult = restTemplate.postForEntity(url, entity, String.class);3. Using Feign
Add the Feign starter dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>Enable Feign in the main class:
@SpringBootApplication
@EnableFeignClients
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}Define a Feign client interface:
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
@RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}Inject and use the client in a controller:
@Autowired
FeignService2 feignService2;
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}To add custom headers (e.g., token), implement a RequestInterceptor :
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token", "
");
}
}Finally, configure the Feign client to use this interceptor:
@FeignClient(url = "${outSide.url}", name = "feignServer", configuration = FeignConfig.class)
public interface TokenDemoClient {
@RequestMapping(value = "/custom/outSideAddToken", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}These three techniques allow Spring Boot developers to choose the most suitable way to interact with external services, from low‑level control with HttpClient to declarative, token‑aware calls with Feign.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.