vince
2023-11-15 6cfe7b4094c1babbedfd6332e9f759c091beaae6
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
package com.fzzy.gateway.util;
 
 
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
import java.net.URLEncoder;
import java.util.Map;
 
/**
 * 网关专用HTTP请求工具类
 */
@Slf4j
public class GatewayHttpUtil {
 
    /**
     * 执行GET请求
     * @param url
     * @param paramsMap
     * @return
     * @throws Exception
     */
    public static String doGet(String url,Map<String, String> paramsMap) throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            String getUrl = url + "?";
            if (paramsMap != null) {
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                  //  getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                    getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8") + "&";
                }
            }
            HttpGet method = new HttpGet(getUrl);
            method.setHeader("Accept", "application/json");
            method.setHeader("charset", "UTF-8");
 
            response = client.execute(method);
//            response.setHeader("Accept", "application/json");
//            response.setHeader("charset", "UTF-8");
 
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity,"UTF-8");
            }
        } catch (Exception e) {
            log.error("http request failed", e);
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
 
        return responseText;
    }
 
}