Chinaunix首页 | 论坛 | 博客
  • 博客访问: 170491
  • 博文数量: 48
  • 博客积分: 365
  • 博客等级: 一等列兵
  • 技术积分: 285
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-11 17:59
文章分类

全部博文(48)

文章存档

2017年(21)

2016年(8)

2013年(2)

2012年(7)

2011年(10)

我的朋友

分类: Java

2011-10-14 16:29:29

原文:http://hi.baidu.com/69hwj/blog/item/9f3a1360f69b2cda8db10d20.html


import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class Test {
    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static void main(String[] args) throws Exception {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
        //URL console = new URL("%3A%2F%2F%2F&hl=zh-CN");
        URL console = new URL("%3A%2F%2F%2F&hl=zh-CN");
        String postData="Passwd=wodemima2&Email=tofzhwj&rmShown=1&GALX=YHymAmp7pkQ";
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());

        conn.setDoInput(true);
        conn.setDoOutput(true);
        BufferedOutputStream hurlBufOus=new BufferedOutputStream(conn.getOutputStream());
        hurlBufOus.write(postData.getBytes());//这里面已经将RequestMethod设置为POST.前面设置无效
        hurlBufOus.flush();

        conn.connect();
        System.out.println(conn.getResponseCode());
        InputStream ins=conn.getInputStream();
        BufferedOutputStream fileBufOus=new BufferedOutputStream(new FileOutputStream("c:/testWeb.html"));
        int read=0;
        byte[] byteBuf=new byte[9412];
        while((read=ins.read(byteBuf))!=-1){
            fileBufOus.write(byteBuf, 0, read);
        }

        if(ins!=null)ins.close();
        if(fileBufOus!=null)fileBufOus.close();
    }
}
阅读(1717) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~