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.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign

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<String,Object> 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 = "<TOKEN>";
    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<String> response = restTemplate.getForEntity(uri, String.class);

// GET with URL variables
Map<String,Object> params = new HashMap<>();
params.put("name", "dada");
ResponseEntity<String> response2 = restTemplate.getForEntity("http://USER-SERVICE/user?name={name}", String.class, params);

// POST example
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer <TOKEN>");
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String,Object> map = getMap(documentId);
HttpEntity<Map> entity = new HttpEntity<>(map, headers);
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity<String> 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", "<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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavafeignSpringBootresttemplateHttpClient
Java Architect Essentials
Written by

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.

0 followers
Reader feedback

How this landed with the community

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.