Backend Development 11 min read

Calling External APIs in Spring Boot: HttpClient, RestTemplate, and Feign Approaches

This article demonstrates three methods for invoking external services in a Spring Boot application—using raw HttpClient, the RestTemplate utility, and Feign clients—providing code examples, configuration steps, and tips for handling headers and tokens.

Top Architect
Top Architect
Top Architect
Calling External APIs in Spring Boot: HttpClient, RestTemplate, and Feign Approaches

1. Introduction

Spring Boot inherits Spring's features and simplifies configuration; sometimes a module needs to call external URLs or services. This guide shows three ways to perform such calls without using Dubbo.

2. Method 1 – Raw HttpClient

Using Apache HttpClient you can build a POST request, set JSON body, add Authorization header, and parse the JSON response.

/* get方式获取入参,插入数据并发起流程 */
@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();
}

/* 使用原生httpClient调用外部接口 */
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");
}

3. Method 2 – RestTemplate

RestTemplate provides convenient methods such as getForEntity , getForObject , and postForEntity . Example of getForEntity with URI builder:

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);

Example of postForEntity with JSON body and custom headers:

@PostMapping("/submit2")
public Object insertFinanceCompensation(@RequestBody JSONObject jsonObject) {
    String documentId = jsonObject.get("documentId").toString();
    return task2Service.submit(documentId);
}

4. Method 3 – Feign Client

Add the Feign starter dependency, enable Feign in the SpringBoot application, and define a Feign interface.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>

Feign client 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);
}
@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
    }
}

Controller can invoke the Feign client:

@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
    return feignService2.getMessage(testDto);
}

The article ends with a reminder to add proper headers and token handling when using Feign.

JavafeignAPISpringBootRestTemplateHttpClient
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.