Backend Development 9 min read

SpringBoot External API Calls: HttpClient, RestTemplate, and Feign Integration

This article explains how to invoke external APIs in a SpringBoot application using three approaches—raw HttpClient, RestTemplate, and Feign—detailing configuration, code examples for GET and POST requests, token handling, and header interception.

Architect's Guide
Architect's Guide
Architect's Guide
SpringBoot External API Calls: HttpClient, RestTemplate, and Feign Integration

SpringBoot inherits Spring's strengths and further simplifies application setup; when a module needs to call external interfaces, three non‑Dubbo methods are available.

1. Raw HttpClient

/*
 * @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<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();
}

The underlying HTTP call can be performed with a plain HttpClient:

/*
 * @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();
    // 要调用的接口url
    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());
        //此处相当于在header里头添加content-type等参数
        s.setContentType("application/json");
        s.setContentEncoding("UTF-8");
        post.setEntity(s);
        //此处相当于在Authorization里头添加Bearer token参数信息
        post.addHeader("Authorization", "Bearer " + assessToken);
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 返回json格式:
            String result = EntityUtils.toString(res.getEntity());
            jsonObject = JSONObject.parseObject(result);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return jsonObject;
}

2. RestTemplate

RestTemplate offers convenient methods such as getForEntity , getForObject , postForEntity , etc. Example of a GET request using a 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> responseEntity = restTemplate.getForEntity(uri, String.class);

GET request with URL variables:

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

POST request example (wrapped in a controller method):

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

3. Feign

Feign simplifies remote calls. Add the dependency spring-cloud-starter-feign , enable with @EnableFeignClients , and define a client interface:

@Service
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
    @RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
    @ResponseBody
    String getMessage(@Valid @RequestBody TestDto testDto);
}

To inject custom headers such as a token, implement a RequestInterceptor :

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //添加token
        requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
    }
}

Finally, use the Feign client in a controller to invoke the external service:

@Autowired
FeignService2 feignService2;

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

The article also includes Maven dependency snippets, application entry‑point annotations, and notes on adding request headers for token propagation.

backendJavafeignSpringBootRestTemplateHttpClient
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

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.