2011-04-10 69 views
1

我有一個應用程序需要能夠發佈到HTTPS的身份驗證請求,然後註冊請求。目前我能夠將我的身份驗證請求發佈到https,並且工作正常。當我嘗試將我的註冊請求發佈到https時,我不斷收到服務器響應,說我需要進行身份驗證。我在嘗試註冊之前進行身份驗證。https會話和發佈問題

服務器的管理員說我可能不會保留會話。我是新來做android和java的東西。我對這個https的東西很陌生。我想知道是否有人可以幫助我在這裏,我不知道這是否是肯定的問題,甚至不知道如何在android中保留https會話。

下面是我的代碼和任何建議非常感謝!提前致謝!!

//my helper class 
public class SmartDBHelper { 

    private static Context tThis; 
    private static SmartDBHelper sDBHObject; 
    private static String macAddress; 
    private static String ipAddress; 
    private static HttpsURLConnection https; 

    /* constructor, private prevents any other class from instantiating */ 
    private SmartDBHelper() { 

    } 

    public static synchronized SmartDBHelper getSDBHObject() { 
     if(sDBHObject == null) { 
      sDBHObject = new SmartDBHelper(); 
     } 
     return sDBHObject; 
    } 

    public Object clone() throws CloneNotSupportedException { 
     throw new CloneNotSupportedException(); 
    } 

    public static synchronized void setSmartContext(SmartApp smartApp) { 
     tThis = (Context) smartApp; 
    } 

    private static synchronized void setMACIPAddress() { 
     WifiManager wifiMan = (WifiManager) tThis.getSystemService (tThis.WIFI_SERVICE); 
     WifiInfo wifiInf = wifiMan.getConnectionInfo(); 
     macAddress = wifiInf.getMacAddress().replace(':', '-'); 
     ipAddress = wifiMan.getDhcpInfo().toString(); 
     int startIndex = ipAddress.indexOf(' '); 
     int endIndex = ipAddress.indexOf(' ', startIndex + 1); 
     ipAddress = ipAddress.substring(startIndex + 1, endIndex); 
    } 

    /* this function is to authenticate with the database 
    * it returns the id_subject, if it is greater than 0 
    * authentication was successful. 
    */ 
    public static synchronized int authenticate() throws MalformedURLException, ProtocolException, IOException { 
     Map<String, String> tempMap = new LinkedHashMap<String, String>(); 
     tempMap.put((String) tThis.getResources().getText(R.string.postAction), (String) tThis.getResources().getText(R.string.postAuthenticate)); 
     tempMap.put((String) tThis.getResources().getText(R.string.authUName), "username"); 
     tempMap.put((String) tThis.getResources().getText(R.string.authPWord), "password"); 
     String tempUrl = "https://ipaddress/health_monitoring/admin.php"; 
     return Integer.parseInt(post(tempUrl, tempMap)); 
    } 

    /* this function is to register the server to the database 
    * not sure of return value 
    */ 
    public static synchronized int registerServer(String nameOfServer, String description) throws MalformedURLException, ProtocolException, IOException { 
     setMACIPAddress(); 
     Map<String, String> tempMap = new LinkedHashMap<String, String>(); 
     tempMap.put((String) tThis.getResources().getText(R.string.postAction), (String) tThis.getResources().getText(R.string.postAddServer)); 
     tempMap.put((String) tThis.getResources().getText(R.string.addServerName), "Phone"); 
     tempMap.put((String) tThis.getResources().getText(R.string.addServerDescription), "Android"); 
     tempMap.put((String) tThis.getResources().getText(R.string.addServerURL), ""); 
     tempMap.put((String) tThis.getResources().getText(R.string.addServerIPAddress), ipAddress); 
     tempMap.put((String) tThis.getResources().getText(R.string.addServerMAC), macAddress); 

     String tempUrl = "https://ipaddress/health_monitoring/admin.php"; 
     return Integer.parseInt(post(tempUrl, tempMap)); 
    } 

    // always verify the host - dont check for certificate 
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 
      public boolean verify(String hostname, SSLSession session) { 
        return true; 
      } 
    }; 

    /** 
    * Trust every server - dont check for any certificate 
    */ 
    private static void trustAllHosts() { 
      // Create a trust manager that does not validate certificate chains 
      TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
          return new java.security.cert.X509Certificate[] {}; 
        } 

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

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

      // Install the all-trusting trust manager 
      try { 
        SSLContext sc = SSLContext.getInstance("TLS"); 
        sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
        HttpsURLConnection 
            .setDefaultSSLSocketFactory(sc.getSocketFactory()); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 

    private static String post(String urlString, Map formParameters) 
    throws MalformedURLException, ProtocolException, IOException { 
     DataOutputStream ostream = null; 

     trustAllHosts(); 
     URL tempUrl; 
     StringBuffer buf = new StringBuffer(); 
     if(formParameters != null) { 
      Set parameters = formParameters.keySet(); 
      Iterator it = parameters.iterator(); 

      for(int i = 0, paramCount = 0; it.hasNext(); i++) { 
       String parameterName = (String) it.next(); 
       String parameterValue = (String) formParameters.get(parameterName); 

       if(parameterValue != null) { 
        parameterValue = URLEncoder.encode(parameterValue); 
        if(paramCount > 0) { 
         buf.append("&"); 
        } 
        buf.append(parameterName); 
        buf.append("="); 
        buf.append(parameterValue); 
        ++paramCount; 
       } 
      } 
     } 
     urlString = urlString + "?" + buf; 
     Log.v("smartdbhelper url string", urlString); 
     tempUrl = new URL(urlString); 
     https = (HttpsURLConnection) tempUrl.openConnection(); 
     https.setHostnameVerifier(DO_NOT_VERIFY); 
     Log.v("smartdbhelper adding post parameters", https.toString()); 
     https.setRequestMethod("POST"); 
     https.setDoInput(true); 
     https.setDoOutput(true); 
     ostream = new DataOutputStream(https.getOutputStream()); 
     ostream.writeBytes(buf.toString()); 

     if(ostream != null) { 
      ostream.flush(); 
      ostream.close(); 
     } 
     Object contents = https.getContent(); 
     InputStream is = (InputStream) contents; 
     StringBuffer buf2 = new StringBuffer(); 
     int c; 
     while((c = is.read()) != -1) { 
      buf2.append((char)c); 
      Log.v("smartdbhelper bugger", buf2.toString()); 
     } 
     //https.disconnect(); 
     return buf2.toString(); 
    } 
} 
+0

「ipaddress」內的url字符串只是爲了保護我使用的服務器的IP地址。 – prolink007 2011-04-10 02:04:18

回答

9

這聽起來像你可能需要處理cookie頭來保存會話。如果是這種情況,這不是特定於HTTPS的。當您發出第一個請求時,您需要找到Set-Cookie響應頭。然後,每個請求都會通過Cookie請求標頭。這裏有一個基本的例子,你可以適應你的情況:

// your first request that does the authentication 
URL authUrl = new URL("https://example.com/authentication"); 
HttpsURLConnection authCon = (HttpsURLConnection) authUrl.openConnection(); 
authCon.connect(); 

// temporary to build request cookie header 
StringBuilder sb = new StringBuilder(); 

// find the cookies in the response header from the first request 
List<String> cookies = authCon.getHeaderFields().get("Set-Cookie"); 
if (cookies != null) { 
    for (String cookie : cookies) { 
     if (sb.length() > 0) { 
      sb.append("; "); 
     } 

     // only want the first part of the cookie header that has the value 
     String value = cookie.split(";")[0]; 
     sb.append(value); 
    } 
} 

// build request cookie header to send on all subsequent requests 
String cookieHeader = sb.toString(); 

// with the cookie header your session should be preserved 
URL regUrl = new URL("https://example.com/register"); 
HttpsURLConnection regCon = (HttpsURLConnection) regUrl.openConnection(); 
regCon.setRequestProperty("Cookie", cookieHeader); 
regCon.connect(); 
+0

這似乎正是我正在尋找的。但是,我如何將其整合到我擁有的代碼中?我有一個發佈功能,顯示在代碼中,我發佈一切。我發送的東西從我的身份驗證發佈到這篇文章和我的註冊內容。那麼,我如何做到這一點,以便當我只有一次獲得這些餅乾?我嘗試了一些東西,每次我嘗試發佈它給「file contents = https.getContent(); 」filenotfound異常。當我有機會時,我會發布更多的代碼,現在我無法發佈它。只是覺得你可能沒有我說的話。 TY。 – prolink007 2011-04-10 16:46:31

+1

我已經嘗試了這幾種不同的方式,他們都沒有工作。 – prolink007 2011-04-12 00:43:42

+0

這並未解決問題。但是,我們放棄了這個想法並做了其他的事情。 – prolink007 2011-12-12 15:05:12