<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    posts - 19, comments - 53, trackbacks - 0, articles - 283
      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
    HttpsURLConnection 擴展 HttpURLConnection,支持各種特定于 https 功能。此類使用 HostnameVerifier 和 SSLSocketFactory。為這兩個類都定義了默認實現(xiàn)。但是,可以根據(jù)每個類(靜態(tài)的)或每個實例來替換該實現(xiàn)。所有新 HttpsURLConnection 實例在創(chuàng)建時將被分配“默認的”靜態(tài)值,通過在連接前調(diào)用每個實例適當?shù)?set 方法可以重寫這些值

    在URL前加https://前綴表明是用SSL加密的。 你的電腦與服務器之間收發(fā)的信息傳輸將更加安全。

    Web服務器啟用SSL需要獲得一個服務器證書并將該證書與要使用SSL的服務器綁定。
    http和https使用的是完全不同的連接方式,用的端口也不一樣,前者是80,后者是443。http的連接很簡單,是無狀態(tài)的,...

    HTTPS協(xié)議是由SSL+HTTP協(xié)議構建的可進行加密傳輸、身份認證的網(wǎng)絡協(xié)議
    要比http協(xié)議安全
    package com.yixun.wap;

    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.cert.*;
    import javax.net.ssl.*;

    public class HttpsURLConnectionTest {

        
    private String url = "https://esales.the9.com/esa/DealerLogin.php?txt_sLogin=andysmile234&pas_sPwd=343211&userstatus=1";

        
    private myX509TrustManager xtm = new myX509TrustManager();

        
    private myHostnameVerifier hnv = new myHostnameVerifier();

        
    public HttpsURLConnectionTest() {
            SSLContext sslContext 
    = null;
            
    try {
                sslContext 
    = SSLContext.getInstance("TLS"); //或SSL
                X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
                sslContext.init(
    null, xtmArray, new java.security.SecureRandom());
            }
     catch (GeneralSecurityException e) {
                e.printStackTrace();
            }

            
    if (sslContext != null{
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            }

            HttpsURLConnection.setDefaultHostnameVerifier(hnv);
        }


        
    public void run() {
            HttpsURLConnection urlCon 
    = null;
            
    try {
                urlCon 
    = (HttpsURLConnection)(new URL(url)).openConnection();
                urlCon.setDoOutput(
    true);
                urlCon.setRequestMethod(
    "POST");
                urlCon.setRequestProperty(
    "Content-Length""1024");
                urlCon.setUseCaches(
    false);
                urlCon.setDoInput(
    true);
                urlCon.getOutputStream().write(
    "request content".getBytes("gbk"));
                urlCon.getOutputStream().flush();
                urlCon.getOutputStream().close();
                BufferedReader in 
    = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
                String line;
                
    while ((line = in.readLine()) != null{
                    System.out.println(line);
                }

                
    // 增加自己的代碼
            }
     catch (MalformedURLException e) {
                e.printStackTrace();
            }
     catch (IOException e) {
                e.printStackTrace();
            }
     catch (Exception e) {
                e.printStackTrace();
            }

        }


        
    public static void main(String[] args) {
            HttpsURLConnectionTest httpsTest 
    = new HttpsURLConnectionTest();
            httpsTest.run();
        }

    }


    /**
     * 重寫三個方法
     * 
    @author Administrator
     *
     
    */

    class myX509TrustManager implements X509TrustManager {
        
        
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }


        
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
            System.out.println(
    "cert: " + chain[0].toString() + ", authType: " + authType);
        }


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

    }


    /**
     * 重寫一個方法
     * 
    @author Administrator
     *
     
    */

    class myHostnameVerifier implements HostnameVerifier {

        
    public boolean verify(String hostname, SSLSession session) {
            System.out.println(
    "Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
            
    return true;
        }

    }


    以下摘自:http://www.zimbio.com/member/kinggod03/articles/HImNQwJm-Lp/ 
     終于完成了博客備份的程序,自己一直想做的事情算是完成了。發(fā)揚懷疑一切的精神,真不放心把自己的帳號告訴其他的公司,讓他們來備份。閑來無事,也為了讓我玩實況累的發(fā)軟的手體驗一下敲代碼的感覺,專心的做完了這個備份博客的程序。總共有300多行,功能其實也很簡單,就是把每篇文章的網(wǎng)頁保存起來 ,但第一次做這種網(wǎng)絡程序,很多都要學習。下面列出幾點收獲:
    1,登陸需要使用SSL協(xié)議,似乎封裝的太好了——只是把代碼烤過來,很簡單,現(xiàn)在也沒懂是啥意思
    2,使用Cookie。登錄之后究竟用什么保存SessionID,頭疼了很長時間。用IE進行登陸,把Cookie設成“提示”,于是所有的暗箱操作都見了陽光。這時才知道,幾乎每個網(wǎng)頁都會用Cookie存些東西,哪還有隱私。百度是必須用Cookie的,否則就無法登陸。這樣有些過分了,應該提供一個選擇。得到Cookie值后需要把“PASSPORTRETRYSTRING=deleted;”去掉,這個字段應該是用于防止重復提交的。如果不去掉,相當于沒有登陸。去掉之后的Cookie值(主要是BDUUSS和BDUID)可以發(fā)送到服務器,這樣就以登陸用戶的身份查看博客了。
    3,對于HTML代碼應該可以用XML的方式來處理,不過我沒有那個耐心,就用字符串的替代查找來實現(xiàn)了,效率不好,可以改進。
    4,連接那部分代碼借鑒了Google提供的博客訪問的源代碼,受益匪淺。百度沒有相應的API,要不然我也不用這么麻煩。
    5,還有許多細節(jié)的東西,比如文件讀寫啦。
    6,看HTML代碼真是頭大!!!
    為了取得信任我就把源代碼貼出來,這也是我不愿意用那些商業(yè)軟件的原因。商業(yè)軟件,賺錢是最主要的,他不信任我,我也不信任他。而我,只不過圖個安心和方便。
    package com.yixun.wap;

    /**
     * 本程序可用于備份百度空間的文章。
     * 18 hours costed.
     * niuys. 
     * 2007.7.11
     
    */

    import java.io.*;
    import java.net.*;
    import java.security.GeneralSecurityException;
    import java.security.cert.X509Certificate;
    import java.util.*;

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

    public class OpticalBackup {
        
    // 把博客信息應編碼
        private String urlString = "https://passport.baidu.com/?login";

        
    // 保存的目錄
        private String saveDir = "L:\\blogBackup";

        
    // 博客的根路徑
        private String spaceRoot = "http://hi.baidu.com/niuys/blog/index/";

        
    private String articleURLHead = "/niuys/blog/item/";

        
    // parameters needed to log in.
        Map parameters = new HashMap();

        
    // 建立連接需要使用cookie提供的sessionID.
        String cookieVal = null;

        
    // Create an anonymous class to trust all certificates.
        
    // This is bad style, you should create a separate class.
        private X509TrustManager xtm = new X509TrustManager() {
            
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }


            
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                
    // System.out.println("cert: " + chain[0].toString() + ", authType:
                
    // "
                
    // + authType);
            }


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

        }
    ;

        
    // Create an class to trust all hosts
        private HostnameVerifier hnv = new HostnameVerifier() {
            
    public boolean verify(String hostname, SSLSession session) {
                
    // System.out.println("hostname: " + hostname);
                return true;
            }

        }
    ;

        
    // In this function we configure our system with a less stringent
        
    // hostname verifier and X509 trust manager. This code is
        
    // executed once, and calls the static methods of HttpsURLConnection
        public OpticalBackup() {
            
    // The parameters needed to log on.
            parameters.put("username""保密");
            parameters.put(
    "password""保密");
            parameters.put(
    "Submit"" 登錄 ");
            parameters.put(
    "tpl""sp");
            parameters.put(
    "tpl_reg""sp");
            parameters.put(
    "u""http://www.baidu.com/");

            
    // check the saveDir
            File dir = new File(saveDir);
            
    if (!dir.exists()) {
                dir.mkdir();
            }


            
    // Initialize the TLS SSLContext with
            
    // our TrustManager
            SSLContext sslContext = null;
            
    try {
                sslContext 
    = SSLContext.getInstance("TLS");
                X509TrustManager[] xtmArray 
    = new X509TrustManager[] {xtm};
                sslContext.init(
    null, xtmArray, new java.security.SecureRandom());
            }
     catch (GeneralSecurityException e) {
                
    // Print out some error message and deal with this exception
                e.printStackTrace();
            }


            
    // Set the default SocketFactory and HostnameVerifier
            
    // for javax.net.ssl.HttpsURLConnection
            if (sslContext != null{
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            }

            HttpsURLConnection.setDefaultHostnameVerifier(hnv);
        }


        
    // the whole process
        public void run() {
            
    try {
                URL url 
    = new URL(urlString);
                HttpURLConnection urlConnection 
    = (HttpURLConnection) url.openConnection();

                
    // Set properties of the connection
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(
    true);
                urlConnection.setUseCaches(
    false);
                urlConnection.setRequestProperty(
    "Content-Type""application/x-www-form-urlencoded");

                
    // Form the POST parameters
                StringBuilder content = new StringBuilder();
                
    boolean first = true;
                Set set 
    = parameters.entrySet();
                Iterator iterator 
    = set.iterator();
                Map.Entry parameter 
    = (Map.Entry) iterator.next();
                
    try {
                    
    while (parameter != null{
                        
    if (!first) {
                            content.append(
    "&");
                        }

                        content.append(URLEncoder.encode((String) parameter.getKey(), 
    "UTF-8")).append("=");
                        content.append(URLEncoder.encode((String) parameter.getValue(), 
    "UTF-8"));
                        first 
    = false;
                        parameter 
    = (Map.Entry) iterator.next();
                    }

                }
     catch (NoSuchElementException e) {
                    e.printStackTrace();
                }


                
    // send the POST request to server
                OutputStream outputStream = null;
                
    try {
                    outputStream 
    = urlConnection.getOutputStream();
                    outputStream.write(content.toString().getBytes(
    "utf-8"));
                    outputStream.flush();
                }
     finally {
                    
    if (outputStream != null{
                        outputStream.close();
                    }

                }


                
    // Retrieve the output
                InputStream inputStream = null;
                StringBuilder outputBuilder 
    = new StringBuilder();
                
    try {
                    
    int responseCode = urlConnection.getResponseCode();
                    
    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inputStream 
    = urlConnection.getInputStream();
                    }
     else {
                        inputStream 
    = urlConnection.getErrorStream();
                    }


                    String string;
                    
    if (inputStream != null{
                        BufferedReader reader 
    = new BufferedReader(new InputStreamReader(inputStream));
                        
    while (null != (string = reader.readLine())) {
                            outputBuilder.append(string).append(
    '\n');
                        }

                    }


                    
    // get the cookie value in the header filelds
                    Map map = urlConnection.getHeaderFields();
                    Collection collection 
    = map.values();
                    Object[] values 
    = collection.toArray();
                    
    // values[4].toString() is nedded .Otherwise,an exception
                    
    // throws. Direct class cast is forbidded.
                    cookieVal = (String) values[4].toString();

                    
    // "replaceAll()" requests that if "[" exits, "]" is nedded
                    
    // too.This is the diffrence from "replace()".
                    cookieVal = cookieVal.replace(']'' ').replace("[PASSPORTRETRYSTRING=deleted; expires=Mon, 01 Jan 1970 00:00:00 GMT; path=/;""");// remedy the first key from cookie
                }
     finally {
                    
    if (inputStream != null{
                        inputStream.close();
                    }

                }


                
    // find all the URLs of the articles you write.
                ArrayList pageURLs = findLinkers();

                
    // save all the articles
                for (int i = 0; i < pageURLs.size(); i++{
                    savePage((String) pageURLs.get(i));
                }

            }
     catch (Exception e) {
                e.printStackTrace();
            }

        }


        
    // save the article with the URL
        private void savePage(String pageURL) {
            
    try {
                
    // create the file to accept the output.The file's name is a part of
                
    // the URL
                File pageFile = new File(saveDir + "\\" + pageURL.substring(36));

                
    // 增量備份
                if (pageFile.exists())
                    
    return;
                FileWriter fw 
    = new FileWriter(pageFile);

                
    // create the connection to the server,and get the results.
                URL url = new URL(pageURL);
                String content 
    = getContentFromURL(url);

                
    // write the contents to the file.
                fw.write(content);
                
    // flush the contents in the buffer.Without
                
    // it,the file's content may be not completed.
                fw.flush();
                fw.close();
            }
     catch (Exception e) {
                e.printStackTrace();
            }

        }


        
    // find all the articles' URL from the html code accepted from the server
        private ArrayList findLinkers() {
            
    // the index of the articles
            int i = 0;
            ArrayList linkers 
    = new ArrayList();
            URL url 
    = null;

            
    try {
                
    while (true{
                    url 
    = new URL(spaceRoot + i);
                    System.out.println(
    "url==" + url);
                    i
    ++;// next index
                    
    // get the content from server
                    String content = getContentFromURL(url);
                    
    // Analyze the content.
                    ArrayList temp = getLinkerFromContent(content);
                    
    if (temp.isEmpty())// no article url exists
                        return linkers;

                    linkers.addAll(temp);
    // combine the URLs
                }

            }
     catch (Exception e) {
                e.printStackTrace();
            }


            
    return linkers;
        }


        
    private ArrayList getLinkerFromContent(String content) {
            ArrayList linkerArray 
    = new ArrayList();
            String linker 
    = null;
            
    // The article's URL begins with "/niuys/blog/item/"
            int index = content.indexOf(articleURLHead);
            
    if (content.indexOf("暫無文章"> 0{// 超過頁數(shù)時會返回包含“暫無文章”的頁,end
                return linkerArray;
            }


            
    // deal with the content
            while (index > 0{
                
    // get the whole URL
                linker = content.substring(index, index + 46);
                content 
    = content.replace(linker, "");
                index 
    = content.indexOf(articleURLHead);
                linker 
    = "http://hi.baidu.com" + linker;
                linkerArray.add(linker);

                System.out.println(
    "linker==" + linker);
            }


            
    return linkerArray;
        }


        
    private String getContentFromURL(URL url) throws Exception {
            HttpURLConnection urlConnection 
    = (HttpURLConnection) url.openConnection();

            
    // Set properties of the connection
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(
    true);
            urlConnection.setUseCaches(
    false);
            urlConnection.setRequestProperty(
    "Content-Type""application/x-www-form-urlencoded");
            urlConnection.addRequestProperty(
    "Cookie", cookieVal);

            
    // Retrieve the output
            InputStream inputStream = null;
            StringBuilder outputBuilder 
    = new StringBuilder();

            
    int responseCode = urlConnection.getResponseCode();
            
    if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream 
    = urlConnection.getInputStream();
            }
     else {
                inputStream 
    = urlConnection.getErrorStream();
            }


            String string;
            
    if (inputStream != null{
                BufferedReader reader 
    = new BufferedReader(new InputStreamReader(inputStream));
                
    while (null != (string = reader.readLine())) {
                    outputBuilder.append(string).append(
    '\n');
                }

                inputStream.close();
                
    return outputBuilder.toString();
            }

            
    return "";
        }


        
    public static void main(String[] args) {
            OpticalBackup backup 
    = new OpticalBackup();
            backup.run();
        }


    }

    主站蜘蛛池模板: 久久最新免费视频| 亚洲国产精品国自产拍电影| 亚洲国产成人久久| 在线免费观看亚洲| 日本亚洲精品色婷婷在线影院| 一区二区三区无码视频免费福利| 亚洲第一页在线播放| 性生交片免费无码看人| 亚洲视频在线免费看| 国产免费拔擦拔擦8X高清在线人| 国产亚洲3p无码一区二区| 国产亚洲免费的视频看| 亚洲中文字幕无码日韩| 中文字幕日本人妻久久久免费| 亚洲av无码一区二区三区乱子伦| 一级成人a毛片免费播放| 亚洲国产高清在线精品一区| 99视频在线精品免费观看6| 亚洲AV成人精品一区二区三区 | 国产大片免费天天看| 国产成人精品日本亚洲专区61 | 久久乐国产精品亚洲综合| 99久久成人国产精品免费| 亚洲中文字幕无码爆乳AV| 国产福利在线免费| 亚洲国产成人久久精品大牛影视 | 亚洲阿v天堂在线| 91频在线观看免费大全| 国产亚洲欧美在线观看| 亚洲午夜无码久久久久| 国产在线a免费观看| 高潮毛片无遮挡高清免费| 亚洲国产精品无码久久久蜜芽| 国产精彩免费视频| 美美女高清毛片视频黄的一免费| 夜夜春亚洲嫩草影院| 欧美大尺寸SUV免费| 精品97国产免费人成视频| 亚洲熟妇无码久久精品| 亚洲国产精品激情在线观看| 1000部羞羞禁止免费观看视频|