Three Ways to Call External APIs in Spring Boot: HttpClient, RestTemplate, and Feign
This article demonstrates how to invoke external services from a Spring Boot application by using raw HttpClient, the RestTemplate utility, and Feign client, providing complete code examples, configuration steps, and tips for handling headers and tokens.
Spring Boot inherits the strengths of the Spring framework and simplifies configuration, but many projects need to call external interfaces or URLs. This guide presents three approaches—raw HttpClient, RestTemplate, and Feign—to achieve external API consumption without Dubbo.
1. Method One: Using 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 {
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
*/
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;
}2. Method Two: Using RestTemplate
RestTemplate provides convenient methods for GET and POST requests. The following examples show how to use getForEntity , getForObject , and postForEntity with both URL strings and URI objects.
// 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 using URL and variables
Map
params = new HashMap<>();
params.put("name", "dada");
ResponseEntity
response2 = restTemplate.getForEntity("http://USER-SERVICE/user?name={name}", String.class, params);
// POST example
@PostMapping("/submit2")
public Object insertFinanceCompensation(@RequestBody JSONObject jsonObject) {
String documentId = jsonObject.get("documentId").toString();
return task2Service.submit(documentId);
}3. Method Three: Using Feign
Feign simplifies HTTP client creation by using declarative interfaces. Add the spring-cloud-starter-feign dependency, enable Feign with @EnableFeignClients , and define a Feign client interface with request mappings.
// Maven dependency
org.springframework.cloud
spring-cloud-starter-feign
1.2.2.RELEASE
// Application entry
@SpringBootApplication
@EnableFeignClients
public class MobilecardApplication {
public static void main(String[] args) {
SpringApplication.run(MobilecardApplication.class, args);
}
}
// Feign client definition
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignService2 {
@RequestMapping(value = "/custom/outSide", method = RequestMethod.POST)
String getMessage(@Valid @RequestBody TestDto testDto);
}
// Controller using Feign
@PostMapping("/test2")
public String test2(@RequestBody TestDto testDto) {
return feignService2.getMessage(testDto);
}
// Adding token via RequestInterceptor
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9...");
}
}The article concludes with a reminder to share the content, join the architecture community, and follow the author for more advanced Spring Boot integration techniques.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.