码迷,mamicode.com
首页 > Web开发 > 详细

JDK原生的HttpURLConnection请求实例

时间:2017-08-03 15:04:45      阅读:222      评论:0      收藏:0      [点我收藏+]

标签: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请求实例

标签:init   pat   ble   jdk   boolean   urlencode   red   str   public   

原文地址:http://www.cnblogs.com/liangblog/p/7279350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!