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

Learn how to integrate external HTTP services in Spring Boot by using raw HttpClient, the RestTemplate utility, and declarative Feign clients, with detailed code examples, token handling, and configuration tips for each approach.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign

1. Introduction

Spring Boot inherits the strengths of the Spring framework and further simplifies configuration, making it easy to build and develop applications. In many projects you need to call external modules or URLs, such as invoking Apaas interfaces during workflow submission.

2. Method 1: Raw HttpClient Request

/*
 * @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 {
    // Convert data to JSON string
    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

RestTemplate also provides APIs for external access. Below are common Get and Post usages.

Get Requests

Two main methods: getForObject and getForEntity. Example of getForEntity 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);
String body = response.getBody();

Another overload using a URL string and 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);
String body = response.getBody();

Post Requests

Three main methods: postForEntity, postForObject, and postForLocation. Example of postForEntity:

@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);
    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);
    return forEntity.toString();
}

4. Method 3: Feign Client

Add the Feign dependency and enable Feign clients:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>
@SpringBootApplication
@EnableFeignClients
public class MobilecardApplication {
    public static void main(String[] args) {
        SpringApplication.run(MobilecardApplication.class, args);
    }
}

Define a mock external service controller:

@PostMapping("/outSide")
public String test(@RequestBody TestDto testDto) {
    return printService.print(testDto);
}

Create a Feign interface for the external API:

@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 Feign client:

@Autowired
FeignService2 feignService2;

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

To add a token header, implement a RequestInterceptor:

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

Use the interceptor in a Feign client:

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

@PostMapping("/testToken")
public String test4(@RequestBody TestDto testDto) {
    return tokenDemoClient.getMessage(testDto);
}

Testing with Postman (example screenshot):

Postman test
Postman test
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
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

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.