https会话和发布问题

时间:2011-04-10 02:01:38

标签: java android http session 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();
    }
}

1 个答案:

答案 0 :(得分:11)

听起来您可能需要处理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();
相关问题