Cookie

In this chapter you will learn:

  1. Get the cookie value from URL
  2. Sending a Cookie to an HTTP Server

The following code gets the cookie value from the server. It looks at the header name Set-Cookie and uses regular expression ;\\s* to split the set cookie command.

import java.net.URL;
import java.net.URLConnection;
//  ja va2  s  .  c o m
public class Main {
  public static void main(String[] argv) throws Exception {
    URL url = new URL("http://java2s.com");
    URLConnection conn = url.openConnection();

    for (int i = 0;; i++) {
      String headerName = conn.getHeaderFieldKey(i);
      String headerValue = conn.getHeaderField(i);

      if (headerName == null && headerValue == null) {
        break;
      }
      if ("Set-Cookie".equalsIgnoreCase(headerName)) {
        String[] fields = headerValue.split(";\\s*");
        for (int j = 1; j < fields.length; j++) {
          if ("secure".equalsIgnoreCase(fields[j])) {
            System.out.println("secure=true");
          } else if (fields[j].indexOf('=') > 0) {
            String[] f = fields[j].split("=");
            if ("expires".equalsIgnoreCase(f[0])) {
              System.out.println("expires"+ f[1]);
            } else if ("domain".equalsIgnoreCase(f[0])) {
              System.out.println("domain"+ f[1]);
            } else if ("path".equalsIgnoreCase(f[0])) {
              System.out.println("path"+ f[1]);
            }
          }
        }
      }
    }
  }
}

The code above generates the following result.

import java.net.URL;
import java.net.URLConnection;
// j  av a  2s  .  c o m
public class Main {
  public static void main(String[] argv) throws Exception {
    URL url = new URL("http://hostname:80");
    URLConnection conn = url.openConnection();

    conn.setRequestProperty("Cookie", "name1=value1; name2=value2");

    conn.connect();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to read a web page from a URL with URLConnection
  2. File size from URL
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface