Get Cookies From http Connection - Java Network

Java examples for Network:URL Download

Description

Get Cookies From http Connection

Demo Code



import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class GetCookiesFromThttpConnection {

    public static void main(String[] args) {
        try {/*from  ww w  .  j a v a 2s  . c  o  m*/
            URL url = new URL("http://www.google.com");
            java.net.URLConnection conn = url.openConnection();
            Map<String, List<String>> headers = conn.getHeaderFields();
            Iterator<String> iter = headers.keySet().iterator();

            while (iter.hasNext()) {
                String key = iter.next();
                if ("Set-Cookie".equalsIgnoreCase(key)) {
                    List<String> values = headers.get(key);
                    for (String value : values) {
                        System.out.println("found ...:" + value);
                        String[] fields = value.split(";\\s*");
                        String cookiValue = fields[0];
                        String expries = null;
                        String path = null;
                        String domain = null;
                        boolean secure = false;

                        for (int i = 0; i < fields.length; i++) {
                            if ("secure".equalsIgnoreCase(fields[i])) {
                                secure = true;
                            } else if (fields[i].indexOf('=') > 0) {
                                String[] f = fields[i].split("=");
                                if ("expires".equalsIgnoreCase(f[0])) {
                                    expries = f[1];
                                } else if ("domain".equalsIgnoreCase(f[0])) {
                                    domain = f[1];
                                } else if ("path".equalsIgnoreCase(f[0])) {
                                    path = f[1];
                                }
                            }
                        }

                        System.out.println("cookiValue :" + cookiValue);
                        System.out.println("expries :" + expries);
                        System.out.println("path :" + path);
                        System.out.println("domain :" + domain);
                        System.out.println("secure :" + secure);
                        System.out.println(" ***************************");

                    }
                }

            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Related Tutorials