HttpClientUtils
作者:互联网
1 public class HttpClientUtils { 2 3 private static final String UTF_8 = "UTF-8"; 4 5 private HttpClientUtils() { 6 } 7 8 public static boolean isHttps(String url) { 9 return "https".equalsIgnoreCase(url.substring(0, 5)); 10 } 11 12 public static String doPost(String url, String params) throws Exception { 13 return doPost(url, params, UTF_8); 14 } 15 16 public static String doPostHttps(String url, String params) throws Exception { 17 return doPostHttps(url, params, UTF_8); 18 } 19 20 public static String doPost(String url, String params, String charset) throws Exception { 21 String contentType = "application/json;charset=" + charset; 22 return doPost(url, params.getBytes(charset), contentType); 23 } 24 25 public static String doPostHttps(String url, String params, String charset) throws Exception { 26 String contentType = "application/json;charset=" + charset; 27 return doPostHttps(url, contentType, params.getBytes(charset)); 28 } 29 30 31 public static String doPost(String url, byte[] content, String contentType) throws Exception { 32 HttpURLConnection conn = null; 33 OutputStream out = null; 34 String rsp = null; 35 try { 36 conn = getConnection(new URL(url), "POST", contentType); 37 out = conn.getOutputStream(); 38 out.write(content); 39 rsp = getResponseAsString(conn); 40 } finally { 41 if (out != null) { 42 out.close(); 43 } 44 if (conn != null) { 45 conn.disconnect(); 46 } 47 } 48 return rsp; 49 } 50 51 52 public static String doGet(String url, Map<String, String> params) throws Exception { 53 return doGet(url, params, UTF_8); 54 } 55 56 public static String doGet(String url, Map<String, String> params, String charset) throws Exception { 57 HttpURLConnection conn = null; 58 String rsp; 59 try { 60 String contentType = "application/x-www-form-urlencoded;charset=" + charset; 61 String query = buildQuery(params, charset); 62 conn = getConnection(buildGetUrl(url, query), "GET", contentType); 63 rsp = getResponseAsString(conn); 64 } finally { 65 if (conn != null) { 66 conn.disconnect(); 67 } 68 } 69 70 return rsp; 71 } 72 73 public static String doGetHttps(String url, String charset) throws Exception { 74 HttpsURLConnection conn = null; 75 String rsp = null; 76 try { 77 String contentType = "application/x-www-form-urlencoded;charset=" + charset; 78 conn = getConnectionHttps(new URL(url), "GET", contentType); 79 rsp = getResponseAsString(conn); 80 } finally { 81 if (conn != null) { 82 conn.disconnect(); 83 } 84 85 } 86 87 return rsp; 88 } 89 90 public static String doPostHttps(String url, String contentType, byte[] content) throws Exception { 91 HttpsURLConnection conn = null; 92 OutputStream out = null; 93 String rsp = null; 94 try { 95 conn = getConnectionHttps(new URL(url), "POST", contentType); 96 out = conn.getOutputStream(); 97 out.write(content); 98 rsp = getResponseAsString(conn); 99 } finally { 100 if (out != null) { 101 out.close(); 102 } 103 104 if (conn != null) { 105 conn.disconnect(); 106 } 107 108 } 109 110 return rsp; 111 } 112 113 114 private static HttpURLConnection getConnection(URL url, String method, String contentType) throws Exception { 115 116 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 117 conn.setDoInput(true); 118 conn.setDoOutput(true); 119 conn.setRequestMethod(method); 120 conn.setRequestProperty("Content-Type", contentType); 121 conn.setRequestProperty("Connection", "Keep-Alive"); 122 conn.setConnectTimeout(5000); 123 conn.setReadTimeout(15000); 124 return conn; 125 } 126 127 private static HttpsURLConnection getConnectionHttps(URL url, String method, String contentType) throws Exception { 128 SSLContext sslContext = null; 129 130 try { 131 sslContext = SSLContext.getInstance("TLSv1.2"); 132 X509TrustManager[] xtmArray = new X509TrustManager[]{new GYX509TrustManager()}; 133 sslContext.init(null, xtmArray, new SecureRandom()); 134 } catch (GeneralSecurityException ignore) { 135 } 136 137 if (sslContext != null) { 138 HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); 139 } 140 141 HttpsURLConnection.setDefaultHostnameVerifier(new GYHostnameVerifier()); 142 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 143 conn.setDoInput(true); 144 conn.setDoOutput(true); 145 conn.setRequestMethod(method); 146 conn.setRequestProperty("Content-Type", contentType); 147 conn.setRequestProperty("Connection", "Keep-Alive"); 148 conn.setConnectTimeout(5000); 149 return conn; 150 } 151 152 private static URL buildGetUrl(String strUrl, String query) throws Exception { 153 URL url = new URL(strUrl); 154 if (StringUtils.isEmpty(query)) { 155 return url; 156 } else { 157 if (StringUtils.isEmpty(url.getQuery())) { 158 if (strUrl.endsWith("?")) { 159 strUrl = strUrl + query; 160 } else { 161 strUrl = strUrl + "?" + query; 162 } 163 } else if (strUrl.endsWith("&")) { 164 strUrl = strUrl + query; 165 } else { 166 strUrl = strUrl + "&" + query; 167 } 168 169 return new URL(strUrl); 170 } 171 } 172 173 174 public static String buildQuery(Map<String, String> params, String charset) throws Exception { 175 if (params != null && !params.isEmpty()) { 176 StringBuilder query = new StringBuilder(); 177 Set<Entry<String, String>> entries = params.entrySet(); 178 boolean hasParam = false; 179 Iterator<Entry<String, String>> querpParams = entries.iterator(); 180 while (querpParams.hasNext()) { 181 Entry<String, String> entry = querpParams.next(); 182 String name = entry.getKey(); 183 String value = entry.getValue(); 184 if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(value)) { 185 if (hasParam) { 186 query.append("&"); 187 } else { 188 hasParam = true; 189 } 190 query.append(name).append("=").append(URLEncoder.encode(value, charset)); 191 } 192 } 193 return query.toString(); 194 } else { 195 return null; 196 } 197 } 198 199 private static String getResponseAsString(HttpURLConnection conn) throws Exception { 200 String charset = getResponseCharset(conn.getContentType()); 201 InputStream es = conn.getErrorStream(); 202 if (conn.getResponseCode() != 200) throw new Exception("请求异常: " + conn.getResponseMessage()); 203 if (es == null) { 204 return getStreamAsString(conn.getInputStream(), charset); 205 } else { 206 String msg = getStreamAsString(es, charset); 207 if (StringUtils.isEmpty(msg)) { 208 throw new Exception(conn.getResponseCode() + ":" + conn.getResponseMessage()); 209 } else { 210 return msg; 211 } 212 } 213 } 214 215 private static String getStreamAsString(InputStream stream, String charset) throws Exception { 216 try ( 217 BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset)); 218 StringWriter writer = new StringWriter(); 219 ) { 220 221 char[] chars = new char[256]; 222 int count; 223 while ((count = reader.read(chars)) > 0) { 224 writer.write(chars, 0, count); 225 } 226 return writer.toString(); 227 } finally { 228 if (stream != null) { 229 stream.close(); 230 } 231 } 232 } 233 234 private static String getResponseCharset(String contentType) { 235 String charset = UTF_8; 236 if (!StringUtils.isEmpty(contentType)) { 237 String[] params = contentType.split(";"); 238 for (int i = 0; i < params.length; ++i) { 239 String param = params[i]; 240 param = param.trim(); 241 if (param.startsWith("charset")) { 242 String[] pair = param.split("=", 2); 243 if (pair.length == 2 && !StringUtils.isEmpty(pair[1])) { 244 charset = pair[1].trim(); 245 } 246 break; 247 } 248 } 249 } 250 return charset; 251 } 252 253 public static String decode(String value) { 254 return decode(value, UTF_8); 255 } 256 257 public static String decode(String value, String charset) { 258 String result = null; 259 if (!StringUtils.isEmpty(value)) { 260 try { 261 result = URLDecoder.decode(value, charset); 262 } catch (Exception var4) { 263 throw new RuntimeException(var4); 264 } 265 } 266 267 return result; 268 } 269 270 public static String encode(String value) { 271 return encode(value, UTF_8); 272 } 273 274 public static String encode(String value, String charset) { 275 String result = null; 276 if (!StringUtils.isEmpty(value)) { 277 try { 278 result = URLEncoder.encode(value, charset); 279 } catch (Exception var4) { 280 throw new RuntimeException(var4); 281 } 282 } 283 284 return result; 285 } 286 287 public static Map<String, String> splitUrlQuery(String query) { 288 Map<String, String> result = new HashMap<>(); 289 String[] pairs = query.split("&"); 290 if (pairs.length > 0) { 291 String[] var3 = pairs; 292 int var4 = pairs.length; 293 for (int var5 = 0; var5 < var4; ++var5) { 294 String pair = var3[var5]; 295 String[] param = pair.split("=", 2); 296 if (param.length == 2) { 297 result.put(param[0], param[1]); 298 } 299 } 300 } 301 302 return result; 303 } 304 305 306 static class GYX509TrustManager implements X509TrustManager { 307 GYX509TrustManager() { 308 } 309 310 public void checkClientTrusted(X509Certificate[] chain, String authType) { 311 // do nothing 312 } 313 314 public void checkServerTrusted(X509Certificate[] chain, String authType) { 315 // do nothing 316 } 317 318 public X509Certificate[] getAcceptedIssuers() { 319 return null; 320 } 321 } 322 323 static class GYHostnameVerifier implements HostnameVerifier { 324 GYHostnameVerifier() { 325 } 326 327 public boolean verify(String hostname, SSLSession session) { 328 return false; 329 } 330 } 331 }
标签:return,String,HttpClientUtils,url,charset,static,conn 来源: https://www.cnblogs.com/yangxijun/p/15703301.html