Java tutorial
/** * Copyright (c) 2011-2017, James Zhan (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wisdombud.right.client.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; /** * HttpKit */ public class HttpKit { private HttpKit() { } /** * https ?? */ private class TrustAnyHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } } /** * https ?? */ private class TrustAnyTrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } private static final String GET = "GET"; private static final String POST = "POST"; private static String CHARSET = "UTF-8"; private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory(); private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpKit().new TrustAnyHostnameVerifier(); private static SSLSocketFactory initSSLSocketFactory() { try { final TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() }; final SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS", // "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); return sslContext.getSocketFactory(); } catch (final Exception e) { throw new RuntimeException(e); } } public static void setCharSet(String charSet) { if (org.apache.commons.lang3.StringUtils.isEmpty(charSet)) { throw new IllegalArgumentException("charSet can not be blank."); } HttpKit.CHARSET = charSet; } private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { final URL _url = new URL(url); final HttpURLConnection conn = (HttpURLConnection) _url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier); } conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(19000); conn.setReadTimeout(19000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (headers != null && !headers.isEmpty()) { for (final Entry<String, String> entry : headers.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } return conn; } /** * Send GET request */ public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers); conn.connect(); return readResponseString(conn); } catch (final Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } public static String get(String url, Map<String, String> queryParas) { return get(url, queryParas, null); } public static String get(String url) { return get(url, null, null); } /** * Send POST request */ public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); conn.connect(); final OutputStream out = conn.getOutputStream(); out.write(data != null ? data.getBytes(CHARSET) : null); out.flush(); out.close(); return readResponseString(conn); } catch (final Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } } public static String post(String url, Map<String, String> queryParas, String data) { return post(url, queryParas, data, null); } public static String post(String url, String data, Map<String, String> headers) { return post(url, null, data, headers); } public static String post(String url, String data) { return post(url, null, data, null); } private static String readResponseString(HttpURLConnection conn) { final StringBuilder sb = new StringBuilder(); InputStream inputStream = null; try { inputStream = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (final Exception e) { throw new RuntimeException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { } } } } private static int readResponseCode(HttpURLConnection conn) { try { return conn.getResponseCode(); } catch (final IOException e) { e.printStackTrace(); } return 404; } /** * Build queryString of the url */ private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) { if (queryParas == null || queryParas.isEmpty()) { return url; } final StringBuilder sb = new StringBuilder(url); boolean isFirst; if (!url.contains("?")) { isFirst = true; sb.append("?"); } else { isFirst = false; } for (final Entry<String, String> entry : queryParas.entrySet()) { if (isFirst) { isFirst = false; } else { sb.append("&"); } final String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { try { value = URLEncoder.encode(value, CHARSET); } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } } sb.append(key).append("=").append(value); } return sb.toString(); } public static String readData(HttpServletRequest request) { BufferedReader br = null; try { final StringBuilder result = new StringBuilder(); br = request.getReader(); for (String line; (line = br.readLine()) != null;) { if (result.length() > 0) { result.append("\n"); } result.append(line); } return result.toString(); } catch (final IOException e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (final IOException e) { } } } } @Deprecated public static String readIncommingRequestData(HttpServletRequest request) { return readData(request); } }