Calling 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 requests, Spring's RestTemplate utilities, and Feign clients—providing code examples, configuration steps, and tips for handling headers and tokens.
Spring Boot inherits Spring's core features and further simplifies application setup; when a module needs to call external interfaces, three Dubbo‑free methods are demonstrated.
Method 1: Raw HttpClient request
@RequestMapping("/submit/{documentId}")
public String submit1(@PathVariable String documentId) throws ParseException {
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();
}
public static JSONObject doPost(JSONObject data) {
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);
StringEntity s = new StringEntity(data.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);
}
return null;
}This code builds a JSON payload, adds an Authorization header with a Bearer token, and sends a POST request using Apache HttpClient.
Method 2: RestTemplate
RestTemplate offers convenient getForEntity , getForObject , and postForEntity methods. Example usages:
// GET 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
response = restTemplate.getForEntity(uri, String.class);
// GET with URL variables
Map
params = new HashMap<>();
params.put("name", "dada");
ResponseEntity
response2 = restTemplate.getForEntity("http://USER-SERVICE/user?name={name}", String.class, params);
// POST using Entity
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + assessToken);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity
entity = new HttpEntity<>(map, headers);
String url = "http://39.103.201.110:30661/xdap-open/open/process/v1/submit";
ResponseEntity
postResponse = restTemplate.postForEntity(url, entity, String.class);These snippets show how to perform GET requests with URI or variable substitution and how to send a JSON body with custom headers using POST.
Method 3: Feign client
Add the Feign starter dependency, enable Feign in the main class, and define a client interface.
org.springframework.cloud
spring-cloud-starter-feign
1.2.2.RELEASE
// Main application
@SpringBootApplication
@EnableFeignClients
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}
// Feign client interface
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
@RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
@ResponseBody
String getMessage(@Valid @RequestBody TestDto testDto);
}
// Controller using Feign
@Autowired
FeignService2 feignService2;
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}To attach tokens or other headers, 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 this configuration can be defined similarly, and the controller can call it to send requests with the token automatically included.
These three techniques give developers flexible options for integrating external HTTP services into Spring Boot applications.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.