简体   繁体   中英

When is the cookie set in HttpURLConnection with Java?

look at these code:

public static String get(String url, Properties parameters) throws MalformedURLException, IOException{
        url = buldGetUrl(url, parameters);
        if(DEBUG) System.out.println("[HTTP GET REQUEST]");
        if(DEBUG) System.out.println(" URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Cookie","JSESSIONID=" + J_SESSION_ID);
        conn.connect();

        if(DEBUG) System.out.println("\n[HTTP GET RESPONSE]");
        if(DEBUG) System.out.println("==== Response Headers =====");
        String serverCookies = conn.getHeaderField("Set-Cookie");
        if(serverCookies != null){
            String[] cookies = serverCookies.split(";");
            for(String s : cookies){
                s = s.trim();
                if(s.split("=")[0].equals("JSESSIONID")){
                    J_SESSION_ID = s.split("=")[1];
                    if(DEBUG) System.out.println(" Session ID Found: " + J_SESSION_ID);
                    break;
                }
            }
        }
        if(DEBUG){
            for(String s : conn.getHeaderFields().keySet()){
                if(s == null)
                    System.out.println(" " + conn.getHeaderField(s));
                else
                    System.out.println(" " + s + "=" + conn.getHeaderField(s));
            }
        }

        if(DEBUG) System.out.println("==== Response Content =====");
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str = null;
        StringBuilder sb = new StringBuilder();
        while ((str = br.readLine()) != null) {
            sb.append(str + System.getProperty("line.separator"));
            if(DEBUG) System.out.println(str);

        }
        br.close();
        return sb.toString();
    }

please notice these three lines:

HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();    
conn.setRequestProperty("Cookie","JSESSIONID=" + J_SESSION_ID);
conn.connect();

URL#openConnection and URL#connect , which method send the request to server? if the answer is openConnection method, how can a cookie be set after a request already been sent? if the answer is connect method, you guess what ? these code below works too, I can get response from server :

url = buldGetUrl(url, parameters);
        if(DEBUG) System.out.println("[HTTP GET REQUEST]");
        if(DEBUG) System.out.println(" URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

        if(DEBUG) System.out.println("\n[HTTP GET RESPONSE]");
        if(DEBUG) System.out.println("==== Response Headers =====");
        String serverCookies = conn.getHeaderField("Set-Cookie");
        if(serverCookies != null){
            String[] cookies = serverCookies.split(";");
            for(String s : cookies){
                s = s.trim();
                if(s.split("=")[0].equals("JSESSIONID")){
                    J_SESSION_ID = s.split("=")[1];
                    if(DEBUG) System.out.println(" Session ID Found: " + J_SESSION_ID);
                    break;
                }
            }
        }
        if(DEBUG){
            for(String s : conn.getHeaderFields().keySet()){
                if(s == null)
                    System.out.println(" " + conn.getHeaderField(s));
                else
                    System.out.println(" " + s + "=" + conn.getHeaderField(s));
            }
        }

        if(DEBUG) System.out.println("==== Response Content =====");
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str = null;
        StringBuilder sb = new StringBuilder();
        while ((str = br.readLine()) != null) {
            sb.append(str + System.getProperty("line.separator"));
            if(DEBUG) System.out.println(str);

        }
        br.close();
        return sb.toString();

The method connect() will Opens a communications link to the resource referenced by this URL, if such a connection has not already been established. getInputStream(), getResponseCode(), or getResponseMessage() methods will create a communication link with server

So in general speaking, #connect() is in fact superfluous, whenever a method of this HttpURLConnection class, that is retrieving a response info (such as #getInputStream()/getResponseCode()/getHeaderFields()/etc.), is invoked, an implicit connect would actually be done. Am I right?

My understanding is based on the below discussion: Using java.net.URLConnection to fire and handle HTTP requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM