Android - Session Cookies

2019-04-02 16:53发布

问题:

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.

回答1:

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


回答2:

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