集册 Java实例教程 从HTTP连接获取Cookies

从HTTP连接获取Cookies

欢马劈雪     最近更新时间:2020-01-02 10:19:05

652
从HTTP连接获取Cookies


import java.io.IOException;

import java.net.MalformedURLException;/*nowjava.com - 时代Java 提供*/

import java.net.URL;

import java.net.URLConnection;


public class Main {

  public static void main(String[] argv) {

    try {

      URL url = new URL("http://hostname:80");

      URLConnection conn = url.openConnection();


      for (int i = 0;; i++) {

        String headerName = conn.getHeaderFieldKey(i);

        String headerValue = conn.getHeaderField(i);


        if (headerName == null && headerValue == null) {
        /*
        n o w  j a v a  . c o m 提 供
        */

          // No more headers

          break;

        }

        if ("Set-Cookie".equalsIgnoreCase(headerName)) {

          // Parse cookie

          String[] fields = headerValue.split(";\\s*");


          String cookieValue = fields[0];

          String expires = null;

          String path = null;

          String domain = null;

          boolean secure = false;


          // Parse each field

          for (int j = 1; j < fields.length; j++) {

            if ("secure".equalsIgnoreCase(fields[j])) {

              secure = true;

            } else if (fields[j].indexOf('=') > 0) {

              String[] f = fields[j].split("=");

              if ("expires".equalsIgnoreCase(f[0])) {

                expires = f[1];

              } else if ("domain".equalsIgnoreCase(f[0])) {

                domain = f[1];
展开阅读全文