Java URL Connection getCookies(URLConnection conn, Map> store)

Here you can find the source of getCookies(URLConnection conn, Map> store)

Description

Retrieves and stores cookies returned by the host on the other side of the open java.net.URLConnection.

License

Apache License

Parameter

Parameter Description
conn a java.net.URLConnection - must be open, or IOException will be thrown
store store

Declaration

@SuppressWarnings("unchecked")
public static void getCookies(URLConnection conn, Map<String, Map<?, ?>> store) 

Method Source Code

//package com.java2s;
/**//from ww w  .j a  v a 2s .c  o m
 * Copyright (C) 2017 Lucifer Wong
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import java.net.URLConnection;

import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static final String COOKIE_VALUE_DELIMITER = ";";
    public static final char DOT = '.';
    public static final char NAME_VALUE_SEPARATOR = '=';
    public static final String SET_COOKIE = "Set-Cookie";

    /**
     * Retrieves and stores cookies returned by the host on the other side of
     * the open java.net.URLConnection.
     * <p>
     * The connection MUST have been opened using the connect() method or a
     * IOException will be thrown.
     * 
     * @author Lucifer Wong
     * @param conn
     *            a java.net.URLConnection - must be open, or IOException will
     *            be thrown
     * @param store
     *            store
     */
    @SuppressWarnings("unchecked")
    public static void getCookies(URLConnection conn, Map<String, Map<?, ?>> store) {
        // let's determine the domain from where these cookies are being sent
        String domain = getCookieDomainFromHost(conn.getURL().getHost());
        Map<String, ConcurrentHashMap<?, ?>> domainStore; // this is where we
        // will store
        // cookies for this
        // domain

        // now let's check the store to see if we have an entry for this domain
        if (store.containsKey(domain)) {
            // we do, so lets retrieve it from the store
            domainStore = (Map<String, ConcurrentHashMap<?, ?>>) store.get(domain);
        } else {
            // we don't, so let's create it and put it in the store
            domainStore = new ConcurrentHashMap<>();
            store.put(domain, domainStore);
        }

        if (domainStore.containsKey("JSESSIONID")) {
            // No need to continually get the JSESSIONID (and set-cookies
            // header) as this does not change throughout the session.
            return;
        }

        // OK, now we are ready to get the cookies out of the URLConnection
        String headerName;
        for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase(SET_COOKIE)) {
                ConcurrentHashMap<String, String> cookie = new ConcurrentHashMap<>();
                StringTokenizer st = new StringTokenizer(conn.getHeaderField(i), COOKIE_VALUE_DELIMITER);

                // the specification dictates that the first name/value pair
                // in the string is the cookie name and value, so let's handle
                // them as a special case:

                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    String key = token.substring(0, token.indexOf(NAME_VALUE_SEPARATOR)).trim();
                    String value = token.substring(token.indexOf(NAME_VALUE_SEPARATOR) + 1);
                    domainStore.put(key, cookie);
                    cookie.put(key, value);
                }

                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    int pos = token.indexOf(NAME_VALUE_SEPARATOR);
                    if (pos != -1) {
                        String key = token.substring(0, pos).toLowerCase().trim();
                        String value = token.substring(token.indexOf(NAME_VALUE_SEPARATOR) + 1);
                        cookie.put(key, value);
                    }
                }
            }
        }
    }

    public static String getCookieDomainFromHost(String host) {
        while (host.indexOf(DOT) != host.lastIndexOf(DOT)) {
            host = host.substring(host.indexOf(DOT) + 1);
        }
        return host;
    }
}

Related

  1. getCharsFromURL(URL url)
  2. getChildren(URL url)
  3. getConnection(URL url)
  4. getConnectionResponseHeaders(URLConnection c)
  5. getContainerUrl(URL url, String resourceInThatDir)
  6. getDataFromServer(URL url)
  7. getDefaultUrlConnection(URL url)
  8. getFeedReader(URL feedUrl)
  9. getFromUrl(String url)