Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign
This article explains how to invoke external services from a Spring Boot application using three approaches—raw HttpClient, Spring's RestTemplate, and Feign—providing detailed code examples, configuration steps, and tips for handling headers and tokens.
1. Introduction
Spring Boot inherits the powerful features of the Spring framework and simplifies configuration, making it easy to build and develop applications. In many projects, modules need to call external URLs or APIs, such as invoking Apaas services during workflow submission.
2. Method 1: Raw HttpClient Request
Using Apache HttpClient you can manually construct HTTP requests, set headers, and parse JSON responses.
/*
* @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
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();
// 要调用的接口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里头添加Bear token参数信息
post.addHeader("Authorization", "Bearer " + assessToken);
HttpResponse res = client.execute(post);
String response1 = EntityUtils.toString(res.getEntity());
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;
}3. Method 2: RestTemplate
RestTemplate provides convenient methods for GET and POST requests. Below are examples of getForEntity, getForObject, and postForEntity.
GET Requests
Two main methods are getForEntity and getForObject . The following shows three overloads of getForEntity :
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
responseEntity = restTemplate.getForEntity(uri, String.class);
String body = responseEntity.getBody();Example using URL variables:
RestTemplate restTemplate = new RestTemplate();
Map
params = new HashMap<>();
params.put("name", "dada");
ResponseEntity
responseEntity = restTemplate.getForEntity("http://USER-SERVICE/user?name={name}", String.class, params);
String body = responseEntity.getBody();Three overloads of getForObject are similar.
POST Requests
RestTemplate offers postForEntity , postForObject , and postForLocation . Below is a sample using 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
map = getMap(documentId);
String jsonStr = JSON.toJSONString(map);
HttpEntity
httpEntity = new HttpEntity<>(map, httpHeaders);
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity
forEntity = restTemplate.postForEntity(url, httpEntity, String.class);
return forEntity.toString();
}4. Method 3: Feign Client
Feign simplifies remote service calls. Add the dependency, enable Feign, and define interfaces.
<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
@ComponentScan(basePackages = {"com.definesys.mpaas", "com.xdap.*"})
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}Define a Feign 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);
}Inject and use the client:
@Autowired
FeignService2 feignService2;
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}To add custom headers such as a token, implement a RequestInterceptor:
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
}
}Finally, a Feign client that uses the interceptor:
@Service
@FeignClient(url = "${outSide.url}", name = "feignServer", configuration = FeignDemoConfig.class)
public interface TokenDemoClient {
@RequestMapping(value = "/custom/outSideAddToken", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}And its controller:
@PostMapping("/testToken")
public String test4(@RequestBody TestDto testDto) {
return tokenDemoClient.getMessage(testDto);
}The article concludes by inviting readers to discuss, join a community, and access additional resources such as interview question collections.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.