1
zj
2025-06-18 69d7ae376a58c399c97ee42e5ff7a13860cb2b7e
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
package util;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpClient {
    public static String get(String url, int timeout) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(timeout);
        connection.setRequestMethod("GET");
 
        connection.connect();
 
        InputStream is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        return readerToString(reader);
    }
 
    public static String post(String url, int timeout, String in) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(timeout);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
 
        connection.setDoOutput(true);
        connection.getOutputStream().write(in.getBytes("UTF-8"));
        connection.connect();
 
        InputStream is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        return readerToString(reader);
    }
 
    private static String readerToString(BufferedReader reader) throws IOException {
        StringBuffer buffer = new StringBuffer();
        String line;
        boolean isFirst = true;
        while ((line = reader.readLine()) != null) {
            if (isFirst) {
                isFirst = false;
            } else {
                buffer.append("\r\n");
            }
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    }
}