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

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

Architect's Guide
Architect's Guide
Architect's Guide
Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign

1. Introduction

Spring Boot inherits Spring's features and further simplifies configuration, making it easy to build applications. In many projects a module needs to call external interfaces or URLs, such as invoking Apaas APIs during workflow submission. This article presents three ways to achieve this without Dubbo.

2. Method 1: Raw HttpClient

Using Apache HttpClient to construct a JSON payload, add Authorization and Content-Type headers, send the request, and process 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<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();
}

/*
 * @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

RestTemplate provides convenient methods for GET and POST requests. The article shows how to use getForEntity, getForObject, and postForEntity with different overloads.

RestTemplate restTemplate = new RestTemplate();
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://USER-SERVICE/user?name={name}")
    .build()
    .expand("dodo")
    .encode();
URI uri = uriComponents.toUri();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> params = new HashMap<>();
params.put("name", "dada");
String result = restTemplate.getForObject("http://USER-SERVICE/user?name={name}", String.class, params);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + assessToken);
httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json");
Map<String, Object> map = getMap(documentId);
String jsonStr = JSON.toJSONString(map);
HttpEntity<Map> httpEntity = new HttpEntity<>(map, httpHeaders);
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity<String> forEntity = restTemplate.postForEntity(url, httpEntity, String.class);

4. Method 3: Feign

Feign simplifies remote calls by defining interfaces. The article covers adding the Feign starter dependency, enabling Feign clients, creating Feign interfaces, and configuring a request interceptor to inject tokens.

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //添加token
        requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
    }
}
@Service
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
    @RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
    @ResponseBody
    String getMessage(@Valid @RequestBody TestDto testDto);
}
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
    return feignService2.getMessage(testDto);
}

Finally, the article mentions testing the endpoints with Postman and adding necessary headers via the interceptor.

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.

backend-developmentSpring Bootfeignresttemplateapi-integrationHttpClient
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

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.