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

This article demonstrates three practical approaches—native HttpClient, Spring's RestTemplate, and Feign client—to invoke external services from a Spring Boot application, providing code examples, configuration details, and tips for handling authentication tokens.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign

1. Introduction

Spring Boot inherits Spring's powerful features and further simplifies configuration, making it easy to build applications. In many projects we need to call external modules or URLs, such as wrapping apaas-provided workflow submission interfaces.

https://github.com/javastacks/spring-boot-best-practice

2. Method 1: Native 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 {
    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);
    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());
            return JSONObject.parseObject(result);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}

3. Method 2: RestTemplate

Spring Boot provides RestTemplate for external API access. Below are examples of GET and POST operations.

GET request

Two main methods are getForEntity and getForObject. Overloads include:

1.getForEntity(String url, Class responseType, Object… urlVariables)
2.getForEntity(URI url, Class responseType)

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

Another overload with URL variables:

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

POST request

Three primary methods are postForEntity, postForObject and postForLocation. Overloads for postForEntity include:

1.postForEntity(String url, Object request, Class responseType, Object... uriVariables)
2.postForEntity(String url, Object request, Class responseType, Map uriVariables)
3.postForEntity(URI url, Object request, Class responseType)

Example of the second overload:

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

public String submit(String documentId) {
    String assessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + assessToken);
    httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json");
    Map<String,Object> map = getMap(documentId);
    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);
    return forEntity.toString();
}

4. Method 3: Feign

Add the Feign starter dependency and enable Feign clients.

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

Enable Feign in the main application:

@SpringBootApplication
@EnableFeignClients
public class MobilecardApplication {
    public static void main(String[] args) {
        SpringApplication.run(MobilecardApplication.class, args);
    }
}

Define a Feign client that calls an external service:

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

Configure a request interceptor to add the token header:

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

Use the Feign client in a controller:

@Autowired
private FeignService2 feignService2;

@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
    return feignService2.getMessage(testDto);
}
Postman test image
Postman test image
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.

JavaSpring Bootfeignresttemplateapi-integrationHttpClient
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.