Android - 会话 Cookie

发布于 2025-01-08 11:31:29 字数 1793 浏览 2 评论 0原文

我需要使用提供会话 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。

公共静态 String getSessionCookie(字符串用户名,字符串密码) {

    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;
}

在清单文件中我设置了权限。

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

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

谢谢。

I need to authenticate username and password with my website which provides Session Cookies.

I am collecting username and password from the EditText on the form and passing it onto authenticate session.

    @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);

    }

The username and password are then checked if they are correct to return the session 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;
}

In the Manifest file I have permission set.

There are no errors but NULL is retuned at the end. I have checked (in debug) the username and password which are correct being passed in the function.

I hope someone can help here.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

£冰雨忧蓝° 2025-01-15 11:31:29

查看此链接:如何制作在Android上使用cookie的http请求?

我认为这是设置和获取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();        
    }
}

Check this link out: How do I make an http request using cookies on Android?

I think that is the preferred way of setting and getting cookies, not looping through the headers like you do (check the end of the function):

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();        
    }
}
贵在坚持 2025-01-15 11:31:29

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

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

For anyone interested; here is the working code. Its an exert of it showing the method.

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文