WangHan
2024-09-12 d5855a4926926698b740bc6c7ba489de47adb68b
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
package tech.powerjob.common.utils;
 
import tech.powerjob.common.exception.PowerJobException;
import okhttp3.*;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
/**
 * 封装 OkHttpClient
 *
 * @author tjq
 * @since 2020/4/6
 */
public class HttpUtils {
 
    private static final OkHttpClient client;
    private static final int HTTP_SUCCESS_CODE = 200;
 
    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }
 
    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        return execute(request);
    }
 
    public static String post(String url, RequestBody requestBody) throws IOException {
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        return execute(request);
    }
 
    private static String execute(Request request) throws IOException {
        try (Response response = client.newCall(request).execute()) {
            int responseCode = response.code();
            if (responseCode == HTTP_SUCCESS_CODE) {
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                }else {
                    return body.string();
                }
            }
            throw new PowerJobException(String.format("http request failed,code=%d", responseCode));
        }
    }
 
}