【问题标题】:Android - Session CookiesAndroid - 会话 Cookie
【发布时间】:2012-03-14 01:47:19
【问题描述】:

我需要通过提供会话 Cookie 的网站验证用户名和密码。

我正在从表单上的 EditText 收集用户名和密码,并将其传递给身份验证会话。

    @Override
    public void onClick(View v) 
    {
        String Username =  username.getText().toString();
        String Password = password.getText().toString();
        String value = LoginAuthenticate.getSessionCookie(Username, Password);
        //This is just check what session value is brought back
        username.setText(value);

    }

然后检查用户名和密码是否正确以返回会话 cookie。

public static String getSessionCookie(String username, String password) {

    String login_url = "http://www.myexperiment.org/session/create";
    URLConnection connection = null;
    String sessionXML = "<session><username>" + username +
            "</username><passsword>" + password +
            "</password></session>";
    String cookieValue = null;
    try 
    {

        URL url = new URL(login_url);
        connection = url.openConnection();

        connection.setRequestProperty("Content-Type", "application/xml");

        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(sessionXML);

        out.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        return null;
    } 
    String headerName = null;
    for (int i =0; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
    {
        if(headerName.equals("Set-Cookie"))
        {
            cookieValue = connection.getHeaderField(i);
        }
    }

    //return connection.getHeaderField("Set-Cookie:");
    return cookieValue;
}

在 Manifest 文件中我设置了权限。

没有错误,但最后会重新调整 NULL。我已经检查(在调试中)在函数中传递正确的用户名和密码。

我希望有人可以在这里提供帮助。

谢谢。

【问题讨论】:

    标签: android login http-post session-cookies


    【解决方案1】:

    查看此链接:How do I make an http request using cookies on Android?

    我认为这是设置和获取 cookie 的首选方式,而不是像你那样循环通过标题(检查函数的结尾):

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.cookie.Cookie;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    
    /**
     * A example that demonstrates how HttpClient APIs can be used to perform
     * form-based logon.
     */
    public class ClientFormLogin {
    
        public static void main(String[] args) throws Exception {
    
            DefaultHttpClient httpclient = new DefaultHttpClient();
    
            HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
    
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
    
            System.out.println("Login form get: " + response.getStatusLine());
            if (entity != null) {
                entity.consumeContent();
            }
            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
    
            HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                    "org=self_registered_users&" +
                    "goto=/portal/dt&" +
                    "gotoOnFail=/portal/dt?error=true");
    
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("IDToken1", "username"));
            nvps.add(new BasicNameValuePair("IDToken2", "password"));
    
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    
            response = httpclient.execute(httpost);
            entity = response.getEntity();
    
            System.out.println("Login form get: " + response.getStatusLine());
            if (entity != null) {
                entity.consumeContent();
            }
    
            System.out.println("Post logon cookies:");
            cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
    
            // When HttpClient instance is no longer needed, 
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();        
        }
    }
    

    【讨论】:

    • 我需要将用户名和密码以特定格式的 XML 文档发送。 String sessionXML = "" + 用户名 + "" + 密码 + "";
    • 我还需要将Content-Type设置为“application/xml”;我该如何使用 NameValuePairs?你能帮忙吗?
    • 我并不是建议您使用名称-值对;这些是针对表单而不是 XML 的。我建议你做的是尝试使用诸如 cookies = httpclient.getCookieStore().getCookies(); 之类的代码。 if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i
    • 感谢您的回复。我设法让这个工作。我意识到我的 xml 中有错字!!! (它总是注定是愚蠢的错误)。为了更好地发布 XML,我更改了几行代码。我非常感谢您的帮助,它促使我对自己的代码提出更多问题。感谢您的帮助。
    【解决方案2】:

    对于任何有兴趣的人;这是工作代码。它是一种展示方法的努力。

    try
    {
        URL url = new URL(login_url);
        connection = (HttpURLConnection) url.openConnection();  
    
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xml");
    
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(sessionXML);
        out.flush();
        out.close();
    
        String headerName = "";
    
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++)
        {       
            if(headerName.equals("Set-Cookie"))
            {
                cookieValue = connection.getHeaderField(i);         
            }
        }
    } 
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(connection != null)
            connection.disconnect();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 2011-04-20
      • 2013-10-06
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 2012-02-09
      • 2012-08-23
      • 1970-01-01
      相关资源
      最近更新 更多