使用Java 11+的HttpClient (推荐)

Java 11引入了新的HttpClient API,位于java.net.http包中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Java11HttpClientExample {
    
    // GET请求示例
    public static void sendGetRequest() throws Exception {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .header("User-Agent", "Java 11 HttpClient")
                .GET()
                .build();
        
        HttpResponse<String> response = client.send(
                request, HttpResponse.BodyHandlers.ofString());
        
        System.out.println("GET Response Code :: " + response.statusCode());
        System.out.println(response.body());
    }
    
    // POST请求示例
    public static void sendPostRequest() throws Exception {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        
        String requestBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .header("User-Agent", "Java 11 HttpClient")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        
        HttpResponse<String> response = client.send(
                request, HttpResponse.BodyHandlers.ofString());
        
        System.out.println("POST Response Code :: " + response.statusCode());
        System.out.println(response.body());
    }
    
    public static void main(String[] args) throws Exception {
        sendGetRequest();
        sendPostRequest();
    }
}

使用Spring的RestTemplate

需要添加Spring Web依赖:

1
2
3
4
5
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.0</version>
</dependency>

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    
    // GET请求示例
    public static void sendGetRequest() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("User-Agent", "RestTemplate");
        
        HttpEntity<String> entity = new HttpEntity<>(headers);
        
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, String.class);
        
        System.out.println("GET Response Code :: " + response.getStatusCodeValue());
        System.out.println(response.getBody());
    }
    
    // POST请求示例
    public static void sendPostRequest() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts";
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("User-Agent", "RestTemplate");
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        
        String requestBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
        
        System.out.println("POST Response Code :: " + response.getStatusCodeValue());
        System.out.println(response.getBody());
    }
    
    public static void main(String[] args) {
        sendGetRequest();
        sendPostRequest();
    }
}

使用OkHttp

添加需要的依赖:

1
2
3
4
5
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

代码示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import okhttp3.*;

import java.io.IOException;

public class OkHttpExample {
    
    // GET请求示例
    public static void sendGetRequest() throws IOException {
        OkHttpClient client = new OkHttpClient();
        
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .addHeader("User-Agent", "OkHttp")
                .build();
        
        try (Response response = client.newCall(request).execute()) {
            System.out.println("GET Response Code :: " + response.code());
            System.out.println(response.body().string());
        }
    }
    
    // POST请求示例
    public static void sendPostRequest() throws IOException {
        OkHttpClient client = new OkHttpClient();
        
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        RequestBody body = RequestBody.create(json, JSON);
        
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .addHeader("User-Agent", "OkHttp")
                .post(body)
                .build();
        
        try (Response response = client.newCall(request).execute()) {
            System.out.println("POST Response Code :: " + response.code());
            System.out.println(response.body().string());
        }
    }
    
    public static void main(String[] args) throws IOException {
        sendGetRequest();
        sendPostRequest();
    }
}

使用Apache HttpClient

需要添加依赖:

1
2
3
4
5
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

代码示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ApacheHttpClientExample {
    
    // GET请求示例
    public static void sendGetRequest() throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");
            
            // 添加请求头
            request.addHeader("User-Agent", "Apache HttpClient");
            
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                System.out.println("GET Response Code :: " + response.getStatusLine().getStatusCode());
                
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                }
            }
        }
    }
    
    // POST请求示例
    public static void sendPostRequest() throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost("https://jsonplaceholder.typicode.com/posts");
            
            // 添加请求头
            request.addHeader("User-Agent", "Apache HttpClient");
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Accept", "application/json");
            
            // 请求体
            String json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
            request.setEntity(new StringEntity(json));
            
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                System.out.println("POST Response Code :: " + response.getStatusLine().getStatusCode());
                
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                }
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        sendGetRequest();
        sendPostRequest();
    }
}

使用Java原生HttpURLConnection

这是Java标准库提供的HTTP客户端,无需额外依赖。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUrlConnectionExample {
    
    // GET请求示例
    public static void sendGetRequest() throws Exception {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        // 设置请求方法
        con.setRequestMethod("GET");
        
        // 添加请求头
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }
    }
    
    // POST请求示例
    public static void sendPostRequest() throws Exception {
        String url = "https://jsonplaceholder.typicode.com/posts";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        // 设置请求方法
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        
        // 启用输出流
        con.setDoOutput(true);
        
        // 请求体
        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        
        try(OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);
        
        if (responseCode == HttpURLConnection.HTTP_CREATED) { // 成功
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            
            System.out.println(response.toString());
        } else {
            System.out.println("POST request not worked");
        }
    }
    
    public static void main(String[] args) throws Exception {
        sendGetRequest();
        sendPostRequest();
    }
}