Fixiaobai
2023-08-26 9e39021f891484b6accb2abc77d34c87bd65681a
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package com.yuanchu.limslaboratory.utils;
 
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
 
/**
 * @Author 张宾
 * @Date 2023/8/26
 */
@Component
public class HttpUtils {
 
    private final String IP="http://localhost:";
 
    @Value("${server.port}")
    private String port;
 
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
 
    public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
 
    final OkHttpClient client
            = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();
 
    public String postJson(String url, Map<String, String> map,String token){
        url=IP+port+url;
        if (map == null || StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }
        Gson gson = new Gson();
        String json = gson.toJson(map);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = builderRequest(url, body, token);
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }
 
    private Request builderRequest(String url,RequestBody body,String token) {
        if(StringUtils.isNotEmpty(token)){
            return new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("X-Token", token)
                    .build();
        }else {
            return new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
        }
    }
 
    /**
     * 需要使用序列化工具将对象序列化成字符串:如gson
     *
     * @param url
     * @param json
     * @return
     */
    public String postJson(String url, String json,String token) {
        url=IP+port+url;
        if (StringUtils.isEmpty(json) || StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = builderRequest(url, body, token);
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }
 
    /**
     * @param url
     * @param queryParamMap
     * @return
     */
    public String get(String url, Map<String, String> queryParamMap, String token){
        url=IP+port+url;
        if (StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }
        System.out.println(url);
        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (queryParamMap != null && queryParamMap.size() != 0) {
            queryParamMap.forEach(builder::addQueryParameter);
        }
        url = builder.build().toString();
        Request request=null;
        if(StringUtils.isNotEmpty(token)){
             request = new Request.Builder()
                    .url(url)
                    .addHeader("X-Token", token)
                    .build();
        }else {
             request = new Request.Builder()
                    .url(url)
                    .build();
        }
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }
}