|
| 1 | +package com.blankj.utilcode.util; |
| 2 | + |
| 3 | +import android.accounts.NetworkErrorException; |
| 4 | +import android.annotation.SuppressLint; |
| 5 | +import android.support.annotation.NonNull; |
| 6 | + |
| 7 | +import java.io.File; |
| 8 | +import java.io.IOException; |
| 9 | +import java.io.InputStream; |
| 10 | +import java.io.UnsupportedEncodingException; |
| 11 | +import java.net.HttpURLConnection; |
| 12 | +import java.net.URL; |
| 13 | +import java.nio.charset.Charset; |
| 14 | +import java.security.cert.X509Certificate; |
| 15 | +import java.util.HashMap; |
| 16 | +import java.util.Map; |
| 17 | + |
| 18 | +import javax.net.ssl.HostnameVerifier; |
| 19 | +import javax.net.ssl.HttpsURLConnection; |
| 20 | +import javax.net.ssl.SSLContext; |
| 21 | +import javax.net.ssl.SSLSession; |
| 22 | +import javax.net.ssl.TrustManager; |
| 23 | +import javax.net.ssl.X509TrustManager; |
| 24 | + |
| 25 | +/** |
| 26 | + * <pre> |
| 27 | + * author: blankj |
| 28 | + * blog : http://blankj.com |
| 29 | + * time : 2019/02/08 |
| 30 | + * desc : utils about http |
| 31 | + * </pre> |
| 32 | + */ |
| 33 | +public class HttpUtils { |
| 34 | + |
| 35 | + private static final int CONNECT_TIMEOUT_TIME = 15000; |
| 36 | + private static final int READ_TIMEOUT_TIME = 19000; |
| 37 | + |
| 38 | + private static final TrustManager[] DEFAULT_TRUST_MANAGERS = new TrustManager[]{ |
| 39 | + new X509TrustManager() { |
| 40 | + @Override |
| 41 | + public X509Certificate[] getAcceptedIssuers() { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + @SuppressLint("TrustAllX509TrustManager") |
| 46 | + @Override |
| 47 | + public void checkClientTrusted(X509Certificate[] chain, String authType) { /**/ } |
| 48 | + |
| 49 | + @SuppressLint("TrustAllX509TrustManager") |
| 50 | + @Override |
| 51 | + public void checkServerTrusted(X509Certificate[] chain, String authType) { /**/ } |
| 52 | + } |
| 53 | + }; |
| 54 | + |
| 55 | + private static final HostnameVerifier DEFAULT_VERIFIER = new HostnameVerifier() { |
| 56 | + @SuppressLint("BadHostnameVerifier") |
| 57 | + @Override |
| 58 | + public boolean verify(String hostname, SSLSession session) { |
| 59 | + return true; |
| 60 | + } |
| 61 | + }; |
| 62 | + |
| 63 | + private static final Config CONFIG = new Config(); |
| 64 | + |
| 65 | + private HttpUtils() { |
| 66 | + throw new UnsupportedOperationException("u can't instantiate me..."); |
| 67 | + } |
| 68 | + |
| 69 | + public static void doGet(@NonNull final Request request, final BaseResponse response) { |
| 70 | + if (response == null) return; |
| 71 | + HttpURLConnection conn = null; |
| 72 | + try { |
| 73 | + conn = getConnection(request, "GET"); |
| 74 | + int responseCode = conn.getResponseCode(); |
| 75 | + if (responseCode == 200) { |
| 76 | + InputStream is = conn.getInputStream(); |
| 77 | + response.onSuccess(is); |
| 78 | + is.close(); |
| 79 | + } else if (responseCode == 301 || responseCode == 302) { |
| 80 | + String location = conn.getHeaderField("Location"); |
| 81 | + doGet(request, response); |
| 82 | + } else { |
| 83 | + response.onError(new NetworkErrorException("Response code: " + responseCode)); |
| 84 | + } |
| 85 | + } catch (IOException e) { |
| 86 | + response.onError(e); |
| 87 | + } finally { |
| 88 | + if (conn != null) { |
| 89 | + conn.disconnect(); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + public static void doPost(@NonNull final Request request, |
| 95 | + final BaseResponse response) { |
| 96 | + if (response == null) return; |
| 97 | + HttpURLConnection conn = null; |
| 98 | + try { |
| 99 | + conn = getConnection(request, "POST"); |
| 100 | + addHeader(conn, request.header); |
| 101 | +// conn.setRequestProperty("accept", "*/*"); |
| 102 | +// conn.setRequestProperty("connection", "Keep-Alive"); |
| 103 | +// conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8"); |
| 104 | +// conn.setRequestProperty("content-length", String.valueOf(sb.length())); |
| 105 | +// conn.setDoOutput(true); |
| 106 | +// |
| 107 | +// PrintWriter printWriter = new PrintWriter(conn.getOutputStream()); |
| 108 | +// printWriter.write(sb.toString()); |
| 109 | +// printWriter.flush(); |
| 110 | +// printWriter.close(); |
| 111 | + int responseCode = conn.getResponseCode(); |
| 112 | + if (responseCode == 200) { |
| 113 | + InputStream is = conn.getInputStream(); |
| 114 | + response.onSuccess(is); |
| 115 | + is.close(); |
| 116 | + } else { |
| 117 | + response.onError(new NetworkErrorException("Response code: " + responseCode)); |
| 118 | + } |
| 119 | + } catch (IOException e) { |
| 120 | + response.onError(e); |
| 121 | + } finally { |
| 122 | + if (conn != null) { |
| 123 | + conn.disconnect(); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + private static HttpURLConnection getConnection(final Request request, final String requestMethod) throws IOException { |
| 129 | + URL httpUrl = new URL(request.url); |
| 130 | + HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); |
| 131 | + if (conn instanceof HttpsURLConnection) { |
| 132 | + HttpsURLConnection httpsConn = (HttpsURLConnection) conn; |
| 133 | + trustAllHosts(httpsConn); |
| 134 | + } |
| 135 | + conn.setConnectTimeout(CONFIG.connectTimeout); |
| 136 | + conn.setReadTimeout(CONFIG.readTimeout); |
| 137 | + conn.setUseCaches(CONFIG.useCaches); |
| 138 | + conn.setRequestMethod(requestMethod); |
| 139 | + return conn; |
| 140 | + } |
| 141 | + |
| 142 | + private static void trustAllHosts(HttpsURLConnection conn) { |
| 143 | + try { |
| 144 | + SSLContext sslContext = SSLContext.getInstance("TLS"); |
| 145 | + sslContext.init(null, DEFAULT_TRUST_MANAGERS, new java.security.SecureRandom()); |
| 146 | + conn.setSSLSocketFactory(sslContext.getSocketFactory()); |
| 147 | + conn.setHostnameVerifier(DEFAULT_VERIFIER); |
| 148 | + } catch (Exception e) { |
| 149 | + e.printStackTrace(); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + private static void addHeader(final HttpURLConnection conn, final Map<String, String> headerMap) { |
| 154 | + if (headerMap != null) { |
| 155 | + for (String key : headerMap.keySet()) { |
| 156 | + conn.setRequestProperty(key, headerMap.get(key)); |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + private static boolean isSpace(final String s) { |
| 162 | + if (s == null) return true; |
| 163 | + for (int i = 0, len = s.length(); i < len; ++i) { |
| 164 | + if (!Character.isWhitespace(s.charAt(i))) { |
| 165 | + return false; |
| 166 | + } |
| 167 | + } |
| 168 | + return true; |
| 169 | + } |
| 170 | + |
| 171 | + public static class Config { |
| 172 | + private int connectTimeout = CONNECT_TIMEOUT_TIME; |
| 173 | + private int readTimeout = READ_TIMEOUT_TIME; |
| 174 | + private boolean useCaches = false; |
| 175 | + } |
| 176 | + |
| 177 | + public static class Request { |
| 178 | + private String url; |
| 179 | + private Map<String, String> header; |
| 180 | + private RequestBody body; |
| 181 | + |
| 182 | + public static Request withUrl(@NonNull final String url) { |
| 183 | + return new Request(url); |
| 184 | + } |
| 185 | + |
| 186 | + private Request(final String url) { |
| 187 | + this.url = url; |
| 188 | + } |
| 189 | + |
| 190 | + public Request addHeader(@NonNull final String name, @NonNull final String value) { |
| 191 | + if (header == null) { |
| 192 | + header = new HashMap<>(); |
| 193 | + } |
| 194 | + header.put(name, value); |
| 195 | + return this; |
| 196 | + } |
| 197 | + |
| 198 | + public Request addHeader(@NonNull final Map<String, String> header) { |
| 199 | + if (this.header == null) { |
| 200 | + this.header = new HashMap<>(); |
| 201 | + } |
| 202 | + this.header.putAll(header); |
| 203 | + return this; |
| 204 | + } |
| 205 | + |
| 206 | + public Request post(@NonNull final RequestBody body) { |
| 207 | + this.body = body; |
| 208 | + return this; |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + public static final class RequestBody { |
| 213 | + String mediaType; |
| 214 | + byte[] content; |
| 215 | + long length; |
| 216 | + |
| 217 | + private RequestBody(String mediaType, byte[] content) { |
| 218 | + this.mediaType = mediaType; |
| 219 | + this.content = content; |
| 220 | + length = content == null ? 0 : content.length; |
| 221 | + } |
| 222 | + |
| 223 | + private static String getCharsetFromMediaType(String mediaType) { |
| 224 | + mediaType = mediaType.toLowerCase().replace(" ", ""); |
| 225 | + int index = mediaType.indexOf("charset="); |
| 226 | + if (index == -1) return "utf-8"; |
| 227 | + int st = index + 8; |
| 228 | + int end = mediaType.length(); |
| 229 | + for (int i = st; i < end; i++) { |
| 230 | + char c = mediaType.charAt(i); |
| 231 | + if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-') { |
| 232 | + end = i; |
| 233 | + break; |
| 234 | + } |
| 235 | + } |
| 236 | + if (st < end) { |
| 237 | + String charset = mediaType.substring(st, end); |
| 238 | + if (Charset.isSupported(charset)) return charset; |
| 239 | + } |
| 240 | + throw new IllegalArgumentException("MediaType is not correct: \"" + mediaType + "\""); |
| 241 | + } |
| 242 | + |
| 243 | + public static RequestBody create(String mediaType, byte[] content) { |
| 244 | + return new RequestBody(mediaType, content); |
| 245 | + } |
| 246 | + |
| 247 | + public static RequestBody form(final Map<String, String> form) { |
| 248 | + return form(form, "utf-8"); |
| 249 | + } |
| 250 | + |
| 251 | + public static RequestBody form(final Map<String, String> form, String charset) { |
| 252 | + String mediaType = "application/x-www-form-urlencoded;charset=" + charset; |
| 253 | + if (form != null) { |
| 254 | + final StringBuilder sb = new StringBuilder(); |
| 255 | + for (String key : form.keySet()) { |
| 256 | + if (sb.length() != 0) { |
| 257 | + sb.append("&"); |
| 258 | + } |
| 259 | + sb.append(key).append("=").append(form.get(key)); |
| 260 | + } |
| 261 | + try { |
| 262 | + return new RequestBody(mediaType, sb.toString().getBytes(charset)); |
| 263 | + } catch (UnsupportedEncodingException e) { |
| 264 | + e.printStackTrace(); |
| 265 | + } |
| 266 | + } |
| 267 | + return new RequestBody(mediaType, null); |
| 268 | + } |
| 269 | + |
| 270 | + public static RequestBody json(final String json) { |
| 271 | + return json(json, "utf-8"); |
| 272 | + } |
| 273 | + |
| 274 | + public static RequestBody json(final String json, String charset) { |
| 275 | + String mediaType = "application/json;charset=" + charset; |
| 276 | + if (json != null) { |
| 277 | + try { |
| 278 | + return new RequestBody(mediaType, json.getBytes(charset)); |
| 279 | + } catch (UnsupportedEncodingException e) { |
| 280 | + e.printStackTrace(); |
| 281 | + } |
| 282 | + } |
| 283 | + return new RequestBody(mediaType, null); |
| 284 | + } |
| 285 | + |
| 286 | + public static RequestBody file(String mediaType, final File file) { |
| 287 | + return file(mediaType, file); |
| 288 | + } |
| 289 | + } |
| 290 | + |
| 291 | + |
| 292 | + public static abstract class BaseResponse { |
| 293 | + public abstract void onSuccess(InputStream is); |
| 294 | + |
| 295 | + public abstract void onError(Throwable t); |
| 296 | + } |
| 297 | +} |
0 commit comments