| | |
| | | |
| | | import okhttp3.*; |
| | | |
| | | import javax.net.ssl.SSLContext; |
| | | import javax.net.ssl.SSLSocketFactory; |
| | | import javax.net.ssl.TrustManager; |
| | | import javax.net.ssl.X509TrustManager; |
| | | import java.io.IOException; |
| | | import java.util.Map; |
| | | import java.util.Optional; |
| | |
| | | public class HttpHandler { |
| | | |
| | | private static final Integer DEFAULT_TIMEOUT_SECONDS = 5; |
| | | private static final MediaType MEDIA_TYPE = MediaType.parse("application/json;charset=utf-8"); |
| | | private static final MediaType MEDIA_TYPE = MediaType.parse("application/json"); |
| | | |
| | | private String uri; |
| | | private String path; |
| | |
| | | } else { |
| | | RequestBody body = RequestBody.create(MEDIA_TYPE, json); |
| | | Request.Builder builder = headerBuilder.url((https?"https://":"http://")+uri+path); |
| | | builder.header("Content-Type", "application/json;charset=UTF-8"); |
| | | builder.header("Content-Type", "application/json"); |
| | | request = builder.post(body).build(); |
| | | |
| | | } |
| | |
| | | .build(); |
| | | } |
| | | |
| | | private OkHttpClient getUnsafeClient(Integer timeout, TimeUnit timeUnit) { |
| | | try { |
| | | TrustManager[] trustAllCerts = new TrustManager[]{ |
| | | new X509TrustManager() { |
| | | @Override |
| | | public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {} |
| | | @Override |
| | | public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {} |
| | | @Override |
| | | public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } |
| | | } |
| | | }; |
| | | |
| | | SSLContext sslContext = SSLContext.getInstance("SSL"); |
| | | sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); |
| | | SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); |
| | | |
| | | return new OkHttpClient.Builder() |
| | | .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]) |
| | | .hostnameVerifier((hostname, session) -> true) |
| | | .connectTimeout(timeout, timeUnit) |
| | | .readTimeout(timeout, timeUnit) |
| | | .build(); |
| | | |
| | | } catch (Exception e) { |
| | | throw new RuntimeException(e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Http协议报文建造者 |
| | | */ |