Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中的HttpsURLConnection連接

Android中的HttpsURLConnection連接

編輯:關於Android編程

[java]
package com.LeadingGH.Core; 
 
import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.URL; 
 
import java.io.*; 
import java.net.*; 
import java.security.*; 
import java.security.cert.*; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 
 
import javax.net.ssl.*; 
 
import android.preference.PreferenceManager; 
 
import com.LeadingGH.Util.Base64; 
 
 
public class VPNAuth 

 
    public String url = ""; 
    public String cookie = ""; 
 
    private myX509TrustManager xtm = new myX509TrustManager(); 
 
    private myHostnameVerifier hnv = new myHostnameVerifier(); 
 
    public VPNAuth(String loginName,String loginPwd,String urlAddress) 
    { 
        SSLContext sslContext = null; 
        if(loginName.equals("") || urlAddress.equals("")) 
            return; 
        try 
        { 
            url = urlAddress+"/SSL/user/PasswordUserLogin?Integrate=true&LoginName=" 
                    + Base64.encode(loginName.getBytes()) 
                    + "&SMS=false&AutoLogin=false&IsTwoAuth=0&LoginPassword=" 
                    + Base64.encode(loginPwd.getBytes()) 
                    + "&APCCode=4567&APCPassword=4567"; 
             
            sslContext = SSLContext.getInstance("SSL"); // 或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); 
        run(url,""); 
    } 
     
    public void VPNLogOut() 
    { 
        String strUrl = "https://58.16.4.27/SSL/user/UserLogout?SMS=false&CS=false&Close=false&Name="+Base64.encode("test".getBytes()); 
        run(strUrl,""); 
        cookie= ""; 
    } 
     
    public String run(String strUrl,String postXML) 
    { 
        HttpsURLConnection urlCon = null; 
        URL urlInstance = null; 
        String firstCookie = ""; 
        String returnVal = ""; 
        StringBuffer sb = new StringBuffer(); 
        try 
        { 
            String params = URLEncoder.encode(postXML); 
            params = "AcceptXML=" + params; 
            urlInstance = new URL(strUrl); 
            urlCon = (HttpsURLConnection) (urlInstance).openConnection(); 
            urlCon.setInstanceFollowRedirects(false); 
            urlCon.setDoOutput(true); 
            urlCon.setDoInput(true); 
            urlCon.setRequestMethod("POST"); 
            urlCon.setRequestProperty("Cookie", cookie); 
            urlCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); 
            urlCon.setRequestProperty("Connection", "Keep-Alive"); 
            urlCon.connect(); 
            byte[] bpara = params.toString().getBytes();  
            urlCon.getOutputStream().write(bpara, 0, bpara.length);  
            urlCon.getOutputStream().flush();  
            urlCon.getOutputStream().close();  
 
 
 
            BufferedReader reader = new BufferedReader(new InputStreamReader( 
                    urlCon.getInputStream())); 
            String redictURL = urlCon.getHeaderField("Location"); 
            String msg = urlCon.getResponseMessage(); 
             
 
            Map<String, List<String>> map = urlCon.getHeaderFields(); 
            Set<String> set = map.keySet(); 
            for (Iterator iterator = set.iterator(); iterator.hasNext();) 
            { 
                String key = (String) iterator.next(); 
                if (key!=null && key.equals("Set-Cookie")) 
                { 
                    System.out.println("key=" + key + ",開始獲取cookie"); 
                    List<String> list = map.get(key); 
                    StringBuilder builder = new StringBuilder(); 
                    for (String str : list) 
                    { 
                        builder.append(str).toString(); 
                    } 
                    firstCookie = builder.toString(); 
                    System.out.println("第一次得到的cookie=" + firstCookie); 
                    if(cookie=="") 
                    { 
                        cookie = firstCookie; 
                    } 
                } 
            } 
             
            String line = null; 
            while ((line = reader.readLine()) != null) 
            { 
                sb.append(line); 
            } 
            reader.close(); 
            Integer statusCode = urlCon.getResponseCode(); 
            if(sb != null) 
            { 
                returnVal = URLDecoder.decode(sb.toString(),"utf-8"); 
            } 
 
        } catch (MalformedURLException e) 
        { 
            e.printStackTrace(); 
        } catch (IOException e) 
        { 
            e.printStackTrace(); 
        } catch (Exception e) 
        { 
            e.printStackTrace(); 
        } finally 
        { 
            if (urlCon != null) 
            { 
                urlCon.disconnect(); 
            } 
            if (urlInstance != null) 
            { 
                urlInstance = null; 
            } 
        } 
        return returnVal; 
    } 
 
    /** */ 
    /**
     * 重寫三個方法
     * 
     * @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; 
        } 
    } 

package com.LeadingGH.Core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.*;

import android.preference.PreferenceManager;

import com.LeadingGH.Util.Base64;


public class VPNAuth
{

 public String url = "";
 public String cookie = "";

 private myX509TrustManager xtm = new myX509TrustManager();

 private myHostnameVerifier hnv = new myHostnameVerifier();

 public VPNAuth(String loginName,String loginPwd,String urlAddress)
 {
  SSLContext sslContext = null;
  if(loginName.equals("") || urlAddress.equals(""))
   return;
  try
  {
   url = urlAddress+"/SSL/user/PasswordUserLogin?Integrate=true&LoginName="
     + Base64.encode(loginName.getBytes())
     + "&SMS=false&AutoLogin=false&IsTwoAuth=0&LoginPassword="
     + Base64.encode(loginPwd.getBytes())
     + "&APCCode=4567&APCPassword=4567";
   
   sslContext = SSLContext.getInstance("SSL"); // 或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);
  run(url,"");
 }
 
 public void VPNLogOut()
 {
  String strUrl = "https://58.16.4.27/SSL/user/UserLogout?SMS=false&CS=false&Close=false&Name="+Base64.encode("test".getBytes());
  run(strUrl,"");
  cookie= "";
 }
 
 public String run(String strUrl,String postXML)
 {
  HttpsURLConnection urlCon = null;
  URL urlInstance = null;
  String firstCookie = "";
  String returnVal = "";
  StringBuffer sb = new StringBuffer();
  try
  {
   String params = URLEncoder.encode(postXML);
   params = "AcceptXML=" + params;
   urlInstance = new URL(strUrl);
   urlCon = (HttpsURLConnection) (urlInstance).openConnection();
   urlCon.setInstanceFollowRedirects(false);
   urlCon.setDoOutput(true);
   urlCon.setDoInput(true);
   urlCon.setRequestMethod("POST");
   urlCon.setRequestProperty("Cookie", cookie);
   urlCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
   urlCon.setRequestProperty("Connection", "Keep-Alive");
   urlCon.connect();
   byte[] bpara = params.toString().getBytes();
   urlCon.getOutputStream().write(bpara, 0, bpara.length);
   urlCon.getOutputStream().flush();
   urlCon.getOutputStream().close();

 

   BufferedReader reader = new BufferedReader(new InputStreamReader(
     urlCon.getInputStream()));
   String redictURL = urlCon.getHeaderField("Location");
   String msg = urlCon.getResponseMessage();
   

   Map<String, List<String>> map = urlCon.getHeaderFields();
   Set<String> set = map.keySet();
   for (Iterator iterator = set.iterator(); iterator.hasNext();)
   {
    String key = (String) iterator.next();
    if (key!=null && key.equals("Set-Cookie"))
    {
     System.out.println("key=" + key + ",開始獲取cookie");
     List<String> list = map.get(key);
     StringBuilder builder = new StringBuilder();
     for (String str : list)
     {
      builder.append(str).toString();
     }
     firstCookie = builder.toString();
     System.out.println("第一次得到的cookie=" + firstCookie);
     if(cookie=="")
     {
      cookie = firstCookie;
     }
    }
   }
   
   String line = null;
   while ((line = reader.readLine()) != null)
   {
    sb.append(line);
   }
   reader.close();
   Integer statusCode = urlCon.getResponseCode();
   if(sb != null)
   {
    returnVal = URLDecoder.decode(sb.toString(),"utf-8");
   }

  } catch (MalformedURLException e)
  {
   e.printStackTrace();
  } catch (IOException e)
  {
   e.printStackTrace();
  } catch (Exception e)
  {
   e.printStackTrace();
  } finally
  {
   if (urlCon != null)
   {
    urlCon.disconnect();
   }
   if (urlInstance != null)
   {
    urlInstance = null;
   }
  }
  return returnVal;
 }

 /** */
 /**
  * 重寫三個方法
  *
  * @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;
  }
 }
}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved