代码之家  ›  专栏  ›  技术社区  ›  nkr1pt

用Java发送带有HTTP请求的cookie

  •  5
  • nkr1pt  · 技术社区  · 16 年前

    服务器分发的cookie在会话结束时过期。

    在我看来,cookie是有效的,因为当我在Firefox中进行相同的调用时,Firefox中存储了一个类似的cookie,它具有相同的名称,以前3个相同的字母开头,长度相同,在会话结束时也会过期。

    // Validate
            url = new URL(URL_VALIDATE);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.connect();
    
            String headerName = null;
            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                if (headerName.equals("Set-Cookie")) {
                    if (conn.getHeaderField(i).startsWith("JSESSIONID")) {
                        cookie = conn.getHeaderField(i).substring(0, conn.getHeaderField(i).indexOf(";")).trim();
                    }
                }
            }
    
            // Get the XML
            url = new URL(URL_XML_TOTALS);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.connect();
    
            // Get the response
            StringBuffer answer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            reader.close();
    
            //Output the response
            System.out.println(answer.toString())
    
    1 回复  |  直到 14 年前
        1
  •  5
  •   McDowell rahul gupta    16 年前

    CookieHandler 做重活。这是我之前做的一个:

    public class MyCookieHandler extends CookieHandler {
      private final Map<String, List<String>> cookies = 
                                                new HashMap<String, List<String>>();
    
      @Override public Map<String, List<String>> get(URI uri,
          Map<String, List<String>> requestHeaders) throws IOException {
        Map<String, List<String>> ret = new HashMap<String, List<String>>();
        synchronized (cookies) {
          List<String> store = cookies.get(uri.getHost());
          if (store != null) {
            store = Collections.unmodifiableList(store);
            ret.put("Cookie", store);
          }
        }
        return Collections.unmodifiableMap(ret);
      }
    
      @Override public void put(URI uri, Map<String, List<String>> responseHeaders)
          throws IOException {
        List<String> newCookies = responseHeaders.get("Set-Cookie");
        if (newCookies != null) {
          synchronized (cookies) {
            List<String> store = cookies.get(uri.getHost());
            if (store == null) {
              store = new ArrayList<String>();
              cookies.put(uri.getHost(), store);
            }
            store.addAll(newCookies);
          }
        }
      }
    }
    

    这个 CookieHandler 假设您的cookie处理对于JVM是全局的;如果您想要每个线程的客户机会话或其他更复杂的事务处理,最好还是坚持使用手动方法。