kongdeqiang
2023-05-11 d4e6ec0389dd8abbcce4ee4f9e5cdad1633491d5
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package com.wgcloud.util;
 
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wgcloud.util.staticvar.StaticKeys;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * @version V1.0
 * @ClassName:RestUtil.java
 * @author: wgcloud
 * @date: 2021年1月16日
 * @Description: RestUtil.java
 * @Copyright: 2019-2021 wgcloud. All rights reserved.
 */
@Component
public class RestUtil {
 
    private Logger logger = LoggerFactory.getLogger(RestUtil.class);
 
    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * post请求接口
     *
     * @param url       接口url
     * @param postStr   提交参数
     * @param keyWord   响应内容需要包含的关键字符
     * @param noKeyWord 响应内容不能包含的关键字
     * @return
     */
    public Map<String, Integer> post(String url, String postStr, String keyWord, String noKeyWord, HashMap<String,String> headerMap) {
        Map<String, Integer> responseMap = new HashMap<>();
        try {
            //默认超过20s后判定失败
            responseMap.put("resTimes", 20000);
            long startTimes = System.currentTimeMillis();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.add("Accept", "*/*");
            headers.set(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
            //如果有设置添加header键值对 添加到header begin
            if (null != headerMap) {
                headers.setAll(headerMap);
            }
            //如果有设置添加header键值对 添加到header end
            HttpEntity<String> httpEntity = new HttpEntity<>(postStr, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            long endTimes = System.currentTimeMillis();
            String resTimes = (endTimes - startTimes) + "";
            //响应时间
            responseMap.put("resTimes", Integer.valueOf(resTimes));
            //状态码
            responseMap.put("heathStatus", responseEntity.getStatusCodeValue());
            logger.debug(responseEntity.getBody());
            //检查响应需要包含设置关键字符
            if (!StringUtils.isEmpty(keyWord)) {
                if (!responseEntity.getBody().contains(keyWord)) {
                    logger.error(url + "----响应内容没有含标识-------" + keyWord);
                    responseMap.put("heathStatus", 500);
                }
            }
            //检查响应不能包含设置关键字符
            if (!StringUtils.isEmpty(noKeyWord)) {
                String[] noKeyWords = noKeyWord.split(StaticKeys.SPLIT_DH);
                for (String noKeyWordChar : noKeyWords) {
                    if (responseEntity.getBody().contains(noKeyWordChar)) {
                        logger.error(url + "----响应内容包含(设置不能包含的关键字)标识-------" + noKeyWordChar);
                        responseMap.put("heathStatus", 500);
                        break;
                    }
                }
            }
            return responseMap;
        } catch (HttpClientErrorException e) {
            logger.error("服务接口检测任务错误", e);
            responseMap.put("heathStatus", e.getRawStatusCode());
            return responseMap;
        } catch (Exception e) {
            logger.error("服务接口检测任务错误", e);
            responseMap.put("heathStatus", 500);
            return responseMap;
        }
    }
 
    public JSONObject post(String url, JSONObject jsonObject) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.parse(jsonObject).toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        return JSONUtil.parseObj(responseEntity.getBody());
    }
 
    public JSONObject post(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        return JSONUtil.parseObj(responseEntity.getBody());
    }
 
    /**
     * get方式请求
     * @param url 请求url
     * @param keyWord  响应内容需要包含字符串
     * @param noKeyWord 响应内容不能包含字符串,多个用逗号隔开
     * @return
     */
    public Map<String, Integer> get(String url, String keyWord, String noKeyWord) {
        Map<String, Integer> responseMap = new HashMap<>();
        try {
            responseMap.put("resTimes", 20000);
            long startTimes = System.currentTimeMillis();
            //v3.3.4去掉时间戳,模拟真实浏览器环境
            /*if (url.indexOf("?") > 0) {
                url = url + "&times=" + startTimes;
            } else {
                url = url + "?times=" + startTimes;
            }*/
            ResponseEntity<String> responseEntity = null;
            if (url.startsWith("https")) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
                headers.add("Accept", "*/*");
                headers.set(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
                HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
                responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            } else {
                responseEntity = restTemplate.getForEntity(url, String.class);
            }
            long endTimes = System.currentTimeMillis();
            String resTimes = (endTimes - startTimes) + "";
            responseMap.put("resTimes", Integer.valueOf(resTimes));
            responseMap.put("heathStatus", responseEntity.getStatusCodeValue());
            logger.debug(responseEntity.getBody());
            //检查响应需要包含设置关键字符
            if (!StringUtils.isEmpty(keyWord)) {
                if (!responseEntity.getBody().contains(keyWord)) {
                    logger.error(url + "----响应内容没有包含关键字标识-------" + keyWord);
                    responseMap.put("heathStatus", 500);
                }
            }
            //检查响应不能包含设置关键字符
            if (!StringUtils.isEmpty(noKeyWord)) {
                String[] noKeyWords = noKeyWord.split(StaticKeys.SPLIT_DH);
                for (String noKeyWordChar : noKeyWords) {
                    if (responseEntity.getBody().contains(noKeyWordChar)) {
                        logger.error(url + "----响应内容包含(设置不能包含的关键字)标识-------" + noKeyWordChar);
                        responseMap.put("heathStatus", 500);
                        break;
                    }
                }
            }
            return responseMap;
        } catch (HttpClientErrorException e) {
            logger.error("服务接口检测任务错误", e);
            responseMap.put("heathStatus", e.getRawStatusCode());
            return responseMap;
        } catch (Exception e) {
            logger.error("服务接口检测任务错误", e);
            responseMap.put("heathStatus", 500);
            return responseMap;
        }
    }
 
 
    public String get(String url) {
        try {
            ResponseEntity<String> responseEntity = null;
            if (url.startsWith("https")) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
                headers.set(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
                HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
                responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            } else {
                responseEntity = restTemplate.getForEntity(url, String.class);
            }
            return responseEntity.getBody();
        } catch (HttpClientErrorException e) {
            logger.error("请求守护进程信息错误", e);
            return "";
        } catch (Exception e) {
            logger.error("请求守护进程信息错误", e);
            return "";
        }
    }
 
}