Using Spring RestTemplate for HTTP Requests: Quick Start and Code Examples
This article introduces Spring's RestTemplate as a simple and convenient HTTP client, compares it with java.net.URLConnection, shows how to add the required dependency, configure the bean, and demonstrates GET and POST request usage with complete code samples and explanations.
RestTemplate is a Spring-provided template class that simplifies HTTP communication compared to using Apache HttpClient or java.net.URLConnection, offering built‑in methods for GET, POST, DELETE and other verbs.
Two approaches to sending HTTP requests are presented: first, using java.net.URLConnection with a full implementation, and second, using RestTemplate with a single line call.
/**
* @param url
* @param param
* @param headers
* @param connectTimeout milliseconds
* @param readTimeout milliseconds
* @return
*/
public static String get(String url, String param, Map<String, String> headers, int connectTimeout, int readTimeout) {
BufferedReader in = null;
StringBuilder builder = new StringBuilder();
try {
String urlNameString = url;
if (param != null) {
urlNameString += "?" + param;
}
URL realUrl = new URL(urlNameString);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", USER_AGENT);
if (connectTimeout > 0) conn.setConnectTimeout(connectTimeout);
if (readTimeout > 0) conn.setReadTimeout(readTimeout);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_CHARSET));
String line;
while ((line = in.readLine()) != null) {
builder.append(line).append("
");
}
}
} catch (Exception e) {
LOGGER.error("HttpUtil.get error.", e);
} finally {
try { if (in != null) in.close(); } catch (Exception e2) { LOGGER.error("HttpUtil.get finally error.", e2); }
}
return builder.toString();
}Using RestTemplate is far simpler:
String result = restTemplate.getForObject(url, String.class);Quick start
1. Add the spring-boot-starter-web dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>2. Configure a RestTemplate bean:
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(6000);
factory.setConnectTimeout(10000);
return factory;
}
}GET request examples
@Test
public void test1() {
String result = restTemplate.getForObject("http://apis.juhe.cn/mobile/get?phone=13429667914&key=1cca71876dc0669109ed3f9501a85e8a", String.class);
System.out.println(result);
}
@Test
public void test2() {
String result = restTemplate.getForObject("http://apis.juhe.cn/mobile/get?phone=13429667914&key=1cca71876dc0669109ed3f9501a85e8a", String.class);
System.out.println("getForObject返回值:" + result);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://apis.juhe.cn/mobile/get?phone=13429667914&key=1cca71876dc0669109ed3f9501a85e8a", String.class);
System.out.println("通过ResponseEntity获取的响应状态码:" + responseEntity.getStatusCode());
System.out.println("通过ResponseEntity获取的响应数据:" + responseEntity.getBody());
Map<String, String> map = new HashMap<>();
map.put("phone", "13429667914");
map.put("key", "1cca71876dc0669109ed3f9501a85e8a");
String resultId = restTemplate.getForObject("http://apis.juhe.cn/mobile/get?phone={phone}&key={key}", String.class, map);
System.out.println("map传参" + resultId);
}Sample output shows successful JSON responses and status codes.
POST request examples
APIs: postForObject: send a request body (often a LinkedMultiValueMap) and receive the response as a String. postForLocation: returns the Location header URI, useful for redirects after login or registration.
Controller used for postForLocation demonstration:
package com.example.restdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/test")
public class HelloController {
/**
* Test postForLocation
*/
@PostMapping("/postLocation")
public String testPostForLocation(String username, String password) {
System.out.println(username);
return "redirect:/index.html";
}
}Test code for POST requests:
@Test
public void test3() {
LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<>();
request.set("key", "9363eb48d9bd745e7627322e2ae78099");
request.set("date", "2021-10-22");
String result = restTemplate.postForObject("http://v.juhe.cn/laohuangli/d", request, String.class);
System.out.println("通过LinkedMultiValueMap对象封装请求参数");
System.out.println(result);
Map<String, String> map = new HashMap<>();
map.put("key", "9363eb48d9bd745e7627322e2ae78099");
map.put("date", "2021-10-22");
String result2 = restTemplate.postForObject("http://v.juhe.cn/laohuangli/d?key={key}&date={date}", request, String.class, map);
System.out.println("通过参数拼接的方式:");
System.out.println(result2);
LinkedMultiValueMap<String, String> req = new LinkedMultiValueMap<>();
req.set("username", "小明");
req.set("password", "decs3465523");
URI uri = restTemplate.postForLocation("http://localhost:8085/test/postLocation", req);
System.out.println("postForLocation请求到的地址为:" + uri);
}The execution results display JSON data returned from the API and the redirected URI from postForLocation.
Summary
The article provides a practical guide to using Spring's RestTemplate for HTTP communication, covering dependency setup, bean configuration, GET and POST request patterns, parameter passing methods, and handling of response entities, making it a useful reference for backend developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
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.
