@RestController
public class RestfulAction {
@PutMapping("put/{param}") public String put(@PathVariable String param) { return "put:" + param; }
@PostMapping("post/{param}") public String post(@PathVariable String param, String id, String name) { return "post:" + param; }
@DeleteMapping("delete/{param}") public String delete(@PathVariable String param) { return "delete:" + param; }
@GetMapping("get/{param}") public String get(@PathVariable String param) { return "get:" + param; }
}
@RequestMapping("dealCon/{param}")
public String dealCon(@PathVariable String param) {
try {
String url = "https://localhost:8080/app/" + param + "/xxx";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(param.toUpperCase()); // GET/POST/PUT/DELETE
conn.setRequestProperty("Accept", "application/json");
if ("post".equals(param)) {
conn.setDoOutput(true);
String body = "id=" + URLEncoder.encode("abc", "UTF-8")
+ "&name=" + URLEncoder.encode("中文", "UTF-8");
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes());
}
}
if (conn.getResponseCode() != 200)
throw new RuntimeException("HTTP error: " + conn.getResponseCode());
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
}
conn.disconnect();
} catch (Exception e) { e.printStackTrace(); }
return "success";
}
@RequestMapping("dealCon2/{param}")
public User dealCon2(@PathVariable String param) {
HttpClient client = HttpClients.createDefault();
User user = null;
try {
if ("get".equals(param)) {
HttpGet get = new HttpGet("https://localhost:8080/app/get/中文");
get.setHeader("Accept", "application/json");
HttpResponse resp = client.execute(get);
user = new ObjectMapper().readValue(resp.getEntity().getContent(), User.class);
} else if ("post".equals(param)) {
HttpPost post = new HttpPost("https://localhost:8080/app/post/xxx");
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("id", "中文"),
new BasicNameValuePair("name", "secret")
);
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse resp = client.execute(post);
user = new ObjectMapper().readValue(resp.getEntity().getContent(), User.class);
}
// PUT/DELETE 類似
} catch (Exception e) { e.printStackTrace(); }
return user;
}
配置 Bean:
<bean id="httpClientFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory">
<property name="connectTimeout" value="10000"/>
<property name="readTimeout" value="10000"/>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
</bean>
Controller 使用:
@Autowired RestTemplate template;
@RequestMapping("RestTem")
public User RestTem(String method) {
User user = null;
if ("get".equals(method)) {
user = template.getForObject("https://localhost:8080/app/get/{id}", User.class, "中文");
ResponseEntity<User> re = template.getForEntity(...); // 可獲取狀態碼、Header
} else if ("post".equals(method)) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token", UUID.randomUUID().toString());
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("id", "中文"); body.add("name", "版本");
HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(body, headers);
user = template.postForObject("https://localhost:8080/app/post/aaa", req, User.class);
} else if ("delete".equals(method)) {
template.delete("https://localhost:8080/app/delete/{id}", "aaa");
} else if ("put".equals(method)) {
template.put("https://localhost:8080/app/put/{id}", null, "bbb");
}
return user;
}
| 維度 | HttpURLConnection | HttpClient | RestTemplate |
|---|---|---|---|
| 依賴 | 無 (JDK 內建) | httpclient jar | spring-web |
| API 風格 | 底層、手動管理 | 流式、鏈式 | 聲明式、模板方法 |
| 連接池 | 無 (需自行實現) | 內建 PoolingHttpClientConnectionManager | 委託 ClientHttpRequestFactory |
| JSON 處理 | 手動 (Jackson/Gson) | 手動 | 內建 HttpMessageConverter |
| 適用場景 | 簡單調用、無 Spring 環境 | 複雜需求 (代理、認證、非同步) | Spring 專案首選 |
現代建議:Spring 5+ 推薦使用
WebClient(WebFlux、非阻塞、Reactive);Spring Boot 3 / Spring 6 已將 RestTemplate 標記為維護模式。