Attempt to read the cookie provided by the server. - Android Network

Android examples for Network:Cookie

Description

Attempt to read the cookie provided by the server.

Demo Code


import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.util.Log;

public class Main{
    public static final String TAG = HttpHelper.class.getSimpleName();
    /**//ww w .  j  a v  a 2s.  c  o  m
     * Attempt to read the cookie provided by the Worddit server.
     * This method fails silently if no cookies are provided.
     * @param connection An HTTP connection to read the cookie from.
     * @param name The name of the cookie to search for
     * @return the contents of the cookie
     */
    public static String readCookie(HttpURLConnection connection,
            String name) {
        Map<String, List<String>> headers = connection.getHeaderFields();
        List<String> values = null;

        for (int i = 1; i <= headers.size(); i++) {
            String headerName = connection.getHeaderFieldKey(i);
            if (headerName.equalsIgnoreCase("Set-Cookie")) {
                values = headers.get(headerName);
            }
        }

        if (values == null) {
            Log.w(TAG, "Warning: no cookies provided");
            return null;
        }

        StringBuffer buf = new StringBuffer();
        for (Iterator<String> iter = values.iterator(); iter.hasNext();) {
            String v = iter.next();
            buf.append(v);
        }

        String fullCookie = buf.toString();
        int i = fullCookie.indexOf(name);
        if (i < 0) {
            Log.w(TAG,
                    String.format("Warning: cookie '%s' not found\n", name));
            return null;
        }
        i += name.length();

        buf = new StringBuffer();
        while (i < fullCookie.length() && fullCookie.charAt(i) != ';') {
            char c = Character.toLowerCase(fullCookie.charAt(i));
            if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f')
                buf.append(c);
            i++;
        }

        return buf.toString();
    }
}

Related Tutorials