JDK原生的HttpURLConnection請求執行個體

來源:互聯網
上載者:User

標籤:init   pat   ble   jdk   boolean   urlencode   red   str   public   

不想說啥,上代碼! 

package com.my.https;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.security.SecureRandom;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.KeyManager;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;public class HttpURLConnectionFactory {    public static int DEFAULT_CONN_TIMEOUR = 30000;    public static HttpURLConnection getConn(String url) throws Throwable {        HttpURLConnection conn = null;        URL http = new URL(url);        if (url.startsWith("https:")) {            HttpsURLConnection httpsConn = null;            SSLContext sslContext = SSLContext.getInstance("TLS");            sslContext.init(new KeyManager[0], new TrustManager[] { new MyX509TrustManager() }, new SecureRandom());            SSLSocketFactory ssf = sslContext.getSocketFactory();            httpsConn = (HttpsURLConnection) http.openConnection();            httpsConn.setSSLSocketFactory(ssf);            httpsConn.setHostnameVerifier(new HostnameVerifier() {                @Override                public boolean verify(String hostname, SSLSession session) {                    return true;                }            });            conn = httpsConn;        } else {            conn = (HttpURLConnection) http.openConnection();        }        return conn;    }    public static String sendGet(HttpURLConnection con) throws Throwable {        addConnProp(con, "GET", true);        BufferedReader br = null;        StringBuffer resultBuffer = new StringBuffer();        try {            br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));            String temp;            while ((temp = br.readLine()) != null) {                resultBuffer.append(temp);            }        } finally {            if (br != null) {                try {                    br.close();                } catch (IOException e) {                    br = null;                    throw new RuntimeException(e);                } finally {                    if (con != null) {                        con.disconnect();                        con = null;                    }                }            }        }        return resultBuffer.toString();    }    public static String sendPost(HttpURLConnection con, String body) throws Throwable {        addConnProp(con, "POST", true);        OutputStream outStream = null;        BufferedReader responseReader = null;        StringBuffer sb = new StringBuffer();        if (body != null) {            outStream = con.getOutputStream();            byte[] data = body.getBytes();            outStream.write(data);            outStream.flush();            outStream.close();        }        int resultCode = con.getResponseCode();        if (HttpURLConnection.HTTP_OK == resultCode) {            String readLine = new String();            responseReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));            while ((readLine = responseReader.readLine()) != null) {                sb.append(readLine).append("\n");            }            responseReader.close();        }        return sb.toString();    }    private static void addConnProp(HttpURLConnection conn, String method, boolean flag) throws Throwable {        conn.setRequestMethod(method);        conn.setConnectTimeout(DEFAULT_CONN_TIMEOUR);        conn.setRequestProperty("accept", "*/*");        // conn.setRequestProperty("Content-Type",        // "application/x-www-form-urlencoded");        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");        conn.setUseCaches(false);        if (flag) {            conn.setDoInput(true);            conn.setDoOutput(true);            conn.setRequestProperty("connection", "Keep-Alive");        }    }}
package com.my.https;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;public class MyX509TrustManager implements X509TrustManager{    @Override    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {            }    @Override    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {            }    @Override    public X509Certificate[] getAcceptedIssuers() {        return null;    }}
MyX509TrustManager.java

還是要說;沒測過,不知道對不對

 

JDK原生的HttpURLConnection請求執行個體

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.