Van333
2022-12-29 d8f66b834134f6b755fd3fb93bb91b56f9d31f6f
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
205
206
207
208
209
210
211
212
213
214
215
216
217
package api.utils;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
 
/**
 * @author  van
 * @date  2022/6/6 11:59
 * @version 1.0
 * msg:
 */public class HttpUtil {
 
 
    private static final String UTF8 = "utf-8";
 
 
    public static String get(String url){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        String result = null;
        try {
            HttpResponse httpResponse = client.execute(get);
            InputStream inStream = httpResponse.getEntity().getContent();
 
            result = streamToString(inStream,UTF8);
 
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
 
    public static String GetWithHeader (String url, List<NameValuePair> urlParameters, Map<String, String> header) throws URISyntaxException {
 
 
        URI finalURI = new URIBuilder(url).setParameters(urlParameters).build();
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(finalURI);
        for(String key: header.keySet()) {
            get.setHeader(key, header.get(key));
        }
 
        String result = null;
        try {
            HttpResponse httpResponse = client.execute(get);
            InputStream inStream = httpResponse.getEntity().getContent();
 
            result = streamToString(inStream, UTF8);
 
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
 
 
 
 
    public static String PostWithHeader (String URL, String json, Map<String, String> header) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        for(String key: header.keySet()) {
            post.setHeader(key, header.get(key));
        }
 
        String result = null;
        try {
            StringEntity s = new StringEntity(json, UTF8);
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
 
            result = streamToString(inStream,UTF8);
 
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
    public static String Post (String URL, String json) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
 
        String result = null;
        try {
            StringEntity s = new StringEntity(json, UTF8);
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
 
            result = streamToString(inStream,UTF8);
 
            inStream.close();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
 
 
 
    public static String streamToString(InputStream in, String encoding){
        // 将流转换为字符串
        try {
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[1024];
            for (int n; (n = in.read(b)) != -1;) {
                sb.append(new String(b, 0, n, encoding));
            }
            return sb.toString();
        }  catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("提取 requestBody 异常", e);
        }
    }
 
    /**
     * <pre>
     * 方法体说明:向远程接口发起请求,返回字符串类型结果
     * @param url 接口地址
     * @param requestMethod 请求类型
     * @param params 传递参数
     * @return String 返回结果
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod, Map<String, String> params){
        //接口返回结果
        String methodResult = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            //将参数集合拼接成特定格式,如name=zhangsan&age=24
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }
            //是否为GET方式请求
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            boolean isPut = "put".equalsIgnoreCase(requestMethod);
            boolean isDelete = "delete".equalsIgnoreCase(requestMethod);
 
            //创建HttpClient连接对象
            DefaultHttpClient client = new DefaultHttpClient();
            HttpRequestBase method = null;
            if(isGet){
                url += "?" + parameters;
                method = new HttpGet(url);
            }else if(isPost){
                method = new HttpPost(url);
                HttpPost postMethod = (HttpPost) method;
                StringEntity entity = new StringEntity(parameters);
                postMethod.setEntity(entity);
            }else if(isPut){
                method = new HttpPut(url);
                HttpPut putMethod = (HttpPut) method;
                StringEntity entity = new StringEntity(parameters);
                putMethod.setEntity(entity);
            }else if(isDelete){
                url += "?" + parameters;
                method = new HttpDelete(url);
            }
            method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
            //设置参数内容类型
            method.addHeader("Content-Type","application/x-www-form-urlencoded");
            //httpClient本地上下文
            HttpClientContext context = null;
            context = HttpClientContext.create();
            //访问接口,返回状态码
            HttpResponse response = client.execute(method, context);
            //返回状态码200,则访问接口成功
            if(response.getStatusLine().getStatusCode()==200){
                methodResult = EntityUtils.toString(response.getEntity());
            }
            client.close();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return methodResult;
    }
 
 
}