首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 調用 RESTful 接口三大方式實戰:HttpURLConnection、HttpClient、RestTemplate

     編輯:Java 綜合教學

Java 調用 RESTful 接口三大方式實戰:HttpURLConnection、HttpClient、RestTemplate

目標服務端點定義

@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; }
}

方式一:HttpURLConnection (JDK 原生、無依賴)

@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";
}

方式二:Apache HttpClient 4.5+ (功能豐富、連接池管理)

@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;
}

方式三:Spring RestTemplate (聲明式、Spring 生態整合)

配置 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;
}

三大方式對比選型

維度HttpURLConnectionHttpClientRestTemplate
依賴無 (JDK 內建)httpclient jarspring-web
API 風格底層、手動管理流式、鏈式聲明式、模板方法
連接池無 (需自行實現)內建 PoolingHttpClientConnectionManager委託 ClientHttpRequestFactory
JSON 處理手動 (Jackson/Gson)手動內建 HttpMessageConverter
適用場景簡單調用、無 Spring 環境複雜需求 (代理、認證、非同步)Spring 專案首選

現代建議:Spring 5+ 推薦使用 WebClient (WebFlux、非阻塞、Reactive);Spring Boot 3 / Spring 6 已將 RestTemplate 標記為維護模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved