HTTPS会话和张贴问题 [英] https Session and posting problem

查看:107
本文介绍了HTTPS会话和张贴问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

予有需要能够发布到https用认证请求,然后寄存器请求的应用程序。目前,我能够发布我的认证请求,HTTPS和它工作正常。当我尝试后我的注册请求到HTTPS我不断收到服务器的响应说,我需要进行身份验证。我验证之前,我尝试注册。

服务器的管理员说,我可能不会preserving了会议。我是新做的东西与Android和Java。而我是新来此HTTPS的东西。我想知道,如果有人可以帮助我在这里,我不知道这是否是肯定的,甚至如何preserve在Android的HTTPS会话的问题。

下面是我的code和任何建议都大大AP preciated !!!!在此先感谢!

  //我的助手类
公共类SmartDBHelper {

    私有静态语境tThis;
    私有静态SmartDBHelper sDBHObject;
    私有静态字符串MACADDRESS;
    私有静态字符串ip地址;
    私有静态HttpsURLConnection HTTPS;

    / *构造,民营prevents任何其它类实例化* /
    私人SmartDBHelper(){

    }

    公共静态同步SmartDBHelper getSDBHObject(){
        如果(sDBHObject == NULL){
            sDBHObject =新SmartDBHelper();
        }
        返回sDBHObject;
    }

    公共对象的clone()抛出CloneNotSupportedException异常{
        抛出新CloneNotSupportedException的();
    }

    公共静态同步无效setSmartContext(SmartApp smartApp){
        tThis =(上下文)smartApp;
    }

    私人静态同步无效setMACIPAddress(){
        WifiManager wifiMan =(WifiManager)tThis.getSystemService(tThis.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();
        。MACADDRESS = wifiInf.getMacAddress()代替(':',' - ');
        ip地址= wifiMan.getDhcpInfo()的toString()。
        INT的startIndex = ipAddress.indexOf('');
        INT endIndex的= ipAddress.indexOf('',在startIndex + 1);
        ip地址= ipAddress.substring(在startIndex + 1,endIndex的);
    }

    / *这个功能是与数据库进行认证
     *它返回id_subject,如果是大于0
     *验证成功。
     * /
    公共静态同步INT验证()抛出MalformedURLException的,的ProtocolException,IOException异常{
        地图<字符串,字符串> tempMap =新的LinkedHashMap<字符串,字符串>();
        tempMap.put((字符串)tThis.getResources()的getText(R.string.postAction),(字符串)tThis.getResources()的getText(R.string.postAuthenticate));
        tempMap.put((字符串)tThis.getResources()的getText(R.string.authUName),用户名。);
        tempMap.put((字符串)tThis.getResources()的getText(R.string.authPWord),密码);
        字符串tempUrl =HTTPS://ipaddress/health_monitoring/admin.php;
        返回的Integer.parseInt(后(tempUrl,tempMap));
    }

    / *这个功能是将服务器注册到数据库
     *不知道返回值
     * /
    公共静态同步INT registerServer(字符串nameOfServer,字符串描述)抛出MalformedURLException的,的ProtocolException,IOException异常{
        setMACIPAddress();
        地图<字符串,字符串> tempMap =新的LinkedHashMap<字符串,字符串>();
        tempMap.put((字符串)tThis.getResources()的getText(R.string.postAction),(字符串)tThis.getResources()的getText(R.string.postAddServer));
        tempMap.put((字符串)tThis.getResources()的getText(R.string.addServerName),手机);
        tempMap.put((字符串)tThis.getResources()的getText(R.string.addServerDescription),机器人);
        tempMap.put((字符串)tThis.getResources()的getText(R.string.addServerURL),);
        tempMap.put((字符串)tThis.getResources()的getText(R.string.addServerIPAddress),ip地址。);
        tempMap.put((字符串)tThis.getResources()的getText(R.string.addServerMAC),MACADDRESS。);

        字符串tempUrl =HTTPS://ipaddress/health_monitoring/admin.php;
        返回的Integer.parseInt(后(tempUrl,tempMap));
    }

    //始终验证主机 - 不检查证书
    最后静态的HostnameVerifier DO_NOT_VERIFY =新的HostnameVerifier(){
            公共布尔验证(字符串主机名,的SSLSession会话){
                    返回true;
            }
    };

    / **
     *信任每个服务器 - 不检查任何证书
     * /
    私有静态无效trustAllHosts(){
            //创建一个信任管理器不验证证书链
            的TrustManager [] trustAllCerts =新的TrustManager [] {新X509TrustManager(){
                    公共java.security.cert.X509Certificate [] getAcceptedIssuers(){
                            返回新java.security.cert.X509Certificate [] {};
                    }

                    公共无效checkClientTrusted(x509证书[]链,
                                    字符串的authType)抛出CertificateException {
                    }

                    公共无效checkServerTrusted(x509证书[]链,
                                    字符串的authType)抛出CertificateException {
                    }
            }};

            //安装所有信任信任管理器
            尝试 {
                    的SSLContext SC = SSLContext.getInstance(TLS);
                    sc.init(NULL,trustAllCerts,新java.security.SecureRandom中的());
                    HttpsURLConnection
                                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            }赶上(例外五){
                    e.printStackTrace();
            }
    }

    私有静态字符串后(字符串urlString,地图formParameters)
    抛出MalformedURLException的,的ProtocolException,IOException异常{
        DataOutputStream类ostream的= NULL;

        trustAllHosts();
        网址tempUrl;
        StringBuffer的BUF =新的StringBuffer();
        如果(formParameters!= NULL){
            设置参数= formParameters.keySet();
            迭代它= parameters.iterator();

            的for(int i = 0,paramCount = 0; it.hasNext();我++){
                字符串参数名称=(字符串)it.next();
                字符串的parameterValue =(字符串)formParameters.get(参数名称);

                如果(的parameterValue!= NULL){
                    的parameterValue = URLEn coder.en code(的parameterValue);
                    如果(paramCount大于0){
                        buf.append(与&);
                    }
                    buf.append(参数名称);
                    buf.append(=);
                    buf.append(的parameterValue);
                    ++ paramCount;
                }
            }
        }
        urlString = urlString +? + BUF;
        Log.v(smartdbhelper URL字符串,urlString);
        tempUrl =新的URL(urlString);
        的https =(HttpsURLConnection)tempUrl.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        Log.v(smartdbhelper加入后的参数,https.toString());
        https.setRequestMethod(POST);
        https.setDoInput(真正的);
        https.setDoOutput(真正的);
        ostream的=新DataOutputStream类(https.getOutputStream());
        ostream.writeBytes(buf.toString());

        如果(ostream的!= NULL){
            ostream.flush();
            ostream.close();
        }
        对象内容= https.getContent();
        InputStream的是=(的InputStream)的内容;
        StringBuffer的BUF2 =新的StringBuffer();
        INT℃;
        而((C = is.​​read())!=  -  1){
            buf2.append((炭)C);
            Log.v(smartdbhelper开溜,buf2.toString());
        }
        //https.disconnect();
        返回buf2.toString();
    }
}
 

解决方案

这听起来像你可能需要处理cookie头至preserve了会议。如果是这样的情况下,这不是针对HTTPS。你需要找到设置Cookie 响应头时,你的第一次请求。在那之后的每个请求你将这些信息传递通过饼干请求头。这里有一个基本的例子,你能适应你的情况:

  //你的第一个要求,即不认证
URL authUrl =新的URL(https://example.com/authentication);
HttpsURLConnection authCon =(HttpsURLConnection)authUrl.openConnection();
authCon.connect();

//临时搭建的请求cookie头
StringBuilder的SB =新的StringBuilder();

//从第一请求中找到的响应报头中的饼干
名单<字符串>饼干= authCon.getHeaderFields()获得(设置Cookie)。
如果(饼干!= NULL){
    对于(字符串饼干:饼干){
        如果(sb.length()大于0){
            sb.append(;);
        }

        //只想cookie头具有值的第一部分
        字符串值= cookie.split(;)[0];
        sb.append(值);
    }
}

//构建请求cookie头发送的所有后续请求
串cookieHeader = sb.toString();

//用cookie头会话应该是preserved
URL regUrl =新的URL(https://example.com/register);
HttpsURLConnection regCon =(HttpsURLConnection)regUrl.openConnection();
regCon.setRequestProperty(曲奇,cookieHeader);
regCon.connect();
 

I have an application that needs to be able to post to https with an authentication request and then a register request. Currently i am able to post my authentication request to https and it works fine. When i try to post my registration request to https i keep getting the server response saying that i need to authenticate. I am authenticating before i attempt to register.

The admin of the server said that i might not be preserving the session. I am new to doing stuff with android and java. And i am new to this https stuff. I was wondering if someone could help me out here, i do not know if that is the problem for sure or even how to preserve an https session in android.

Below is my code and any suggestions are greatly appreciated!!!! Thanks in advance!!

//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();
    }
}

解决方案

It sounds like you probably need to handle cookie headers to preserve the session. If that's the case this isn't specific to HTTPS. You'll need to find the Set-Cookie response header when you make the first request. Then every request after that you'll pass those through a Cookie request header. Here's a basic example that you can adapt for your case:

// 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();

这篇关于HTTPS会话和张贴问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆