Comprehensive Guide to Using Spring RestTemplate for HTTP Requests

This article provides a detailed tutorial on Spring's RestTemplate class, covering its overview, setup, and extensive examples of GET, POST, file download, header handling, dynamic URL parameters, and integration with HttpClient and OkHttp, along with complete code snippets and best‑practice recommendations for backend Java development.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Comprehensive Guide to Using Spring RestTemplate for HTTP Requests

1. RestTemplate Overview

RestTemplate simplifies HTTP communication in Spring applications by providing convenient methods that correspond to HTTP verbs such as GET, POST, PUT, DELETE, and OPTIONS, similar to HttpClient or OkHttp but with easier usage.

2. Example Code

The source code is hosted at https://gitee.com/javacode2018/springmvc-series. Controllers are placed in RestTemplateTestController and test cases in RestTemplateTest.

3. Sending GET Requests

3.1 Simple GET

Controller:

@GetMapping("/test/get")
@ResponseBody
public BookDto get(){
    return new BookDto(1, "SpringMVC系列");
}

Client usage:

RestTemplate rt = new RestTemplate();
String url = "http://localhost:8080/chat16/test/get";
BookDto dto = rt.getForObject(url, BookDto.class);
System.out.println(dto);

ResponseEntity<BookDto> resp = rt.getForEntity(url, BookDto.class);
System.out.println(resp.getStatusCode());
System.out.println("Headers:" + resp.getHeaders());
System.out.println(resp.getBody());

3.2 URL with Dynamic Parameters

@GetMapping("/test/get/{id}/{name}")
@ResponseBody
public BookDto get(@PathVariable("id") Integer id, @PathVariable("name") String name){
    return new BookDto(id, name);
}

Client usage with uriVariables map:

String url = "http://localhost:8080/chat16/test/get/{id}/{name}";
Map<String,String> vars = new HashMap<>();
vars.put("id","1");
vars.put("name","SpringMVC系列");
BookDto dto = rt.getForObject(url, BookDto.class, vars);
System.out.println(dto);

3.3 Generic Return Types

@GetMapping("/test/getList")
@ResponseBody
public List<BookDto> getList(){
    return Arrays.asList(new BookDto(1,"Spring高手系列"), new BookDto(2,"SpringMVC系列"));
}

Client must use exchange with ParameterizedTypeReference:

ResponseEntity<List<BookDto>> resp = rt.exchange(
    url,
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<BookDto>>(){}
);
List<BookDto> list = resp.getBody();
System.out.println(list);

3.4 Download Small File

@GetMapping("/test/downFile")
@ResponseBody
public HttpEntity<InputStreamResource> downFile(){
    InputStream is = this.getClass().getResourceAsStream("/1.txt");
    InputStreamResource res = new InputStreamResource(is);
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=1.txt");
    return new HttpEntity<>(res, headers);
}

Client reads the byte array:

ResponseEntity<byte[]> resp = rt.getForEntity(url, byte[].class);
String content = new String(resp.getBody());
System.out.println(content);

3.5 Download Large File

Use execute with a ResponseExtractor to stream the response and avoid OOM.

String result = rt.execute(url, HttpMethod.GET, null, response -> {
    InputStream body = response.getBody();
    return IOUtils.toString(body, "UTF-8");
}, new HashMap<>());
System.out.println(result);

3.6 Sending Headers

HttpHeaders headers = new HttpHeaders();
headers.add("header-1","V1");
headers.add("header-2","Spring");
RequestEntity<Void> req = new RequestEntity<>(null, headers, HttpMethod.GET, URI.create(url));
ResponseEntity<Map<String,List<String>>> resp = rt.exchange(req, new ParameterizedTypeReference<Map<String,List<String>>>(){});
System.out.println(resp.getBody());

3.7 Combined Example (Headers + Dynamic URL)

HttpHeaders headers = new HttpHeaders();
headers.add("header-1","V1");
Map<String,String> uriVars = Map.of("path1","v1","path2","v2");
HttpEntity<Void> entity = new HttpEntity<>(null, headers);
ResponseEntity<Map<String,Object>> resp = rt.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<Map<String,Object>>(){}, uriVars);
System.out.println(resp.getBody());

4. POST Requests

4.1 Content‑Type Overview

Common types: application/x-www-form-urlencoded, multipart/form-data, application/json.

4.2 Form URL‑Encoded

@PostMapping("/test/form1")
@ResponseBody
public BookDto form1(BookDto dto){
    return dto;
}

Client:

MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
body.add("id","1");
body.add("name","SpringMVC系列");
BookDto result = rt.postForObject(url, body, BookDto.class);
System.out.println(result);

4.3 File Upload (multipart/form-data)

@PostMapping("/test/form2")
@ResponseBody
public Map<String,String> form2(@RequestParam("file1") MultipartFile file){
    Map<String,String> meta = new HashMap<>();
    meta.put("文件名", file.getOriginalFilename());
    meta.put("文件类型", file.getContentType());
    meta.put("文件大小(byte)", String.valueOf(file.getSize()));
    return meta;
}

Client uses FileSystemResource (or InputStreamResource / ByteArrayResource) as the file value:

MultiValueMap<String,Object> body = new LinkedMultiValueMap<>();
body.add("file1", new FileSystemResource("./src/main/java/com/javacode2018/.../UserDto.java"));
HttpHeaders headers = new HttpHeaders();
headers.add("header1","v1");
RequestEntity<MultiValueMap<String,Object>> req = new RequestEntity<>(body, headers, HttpMethod.POST, URI.create(url));
ResponseEntity<Map<String,String>> resp = rt.exchange(req, new ParameterizedTypeReference<Map<String,String>>(){ });
System.out.println(resp.getBody());

4.4 JSON Body (Object)

@PostMapping("/test/form4")
@ResponseBody
public BookDto form4(@RequestBody BookDto dto){
    return dto;
}

Client sends a Java object which RestTemplate serializes to JSON:

BookDto body = new BookDto(1,"SpringMVC系列");
BookDto result = rt.postForObject(url, body, BookDto.class);
System.out.println(result);

4.5 JSON Body (Generic List)

@PostMapping("/test/form5")
@ResponseBody
public List<BookDto> form5(@RequestBody List<BookDto> list){
    return list;
}

Client can also send a raw JSON string, but must set Content-Type: application/json explicitly:

String json = "[{\"id\":1,\"name\":\"SpringMVC系列\"},{\"id\":2,\"name\":\"MySQL系列\"}]";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RequestEntity<String> req = new RequestEntity<>(json, headers, HttpMethod.POST, URI.create(url));
ResponseEntity<List<BookDto>> resp = rt.exchange(req, new ParameterizedTypeReference<List<BookDto>>(){});
System.out.println(resp.getBody());

5. DELETE, PUT, OPTIONS

RestTemplate provides delete, put and optionsForAllow methods that accept URL strings, URI objects or URL templates with variables.

6. Integrating HttpClient

By creating a custom HttpClient with connection pooling, SSL settings, and timeouts, and wiring it into a HttpComponentsClientHttpRequestFactory, you can replace the default JDK implementation for better performance.

7. Integrating OkHttp

Simply instantiate RestTemplate with new OkHttp3ClientHttpRequestFactory() after adding the OkHttp dependency.

8. Summary

RestTemplate offers a concise API for various HTTP interactions in Spring; understanding its methods, request/response handling, and how to plug in alternative HTTP clients enables developers to write clean, efficient backend code.

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.

BackendJavaspringHTTPAPIresttemplateSpring MVC
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

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.