在Java中使用HTTP请求发送cookie

问题描述:

我想通过创建一系列Http请求来获取java客户端中的某个cookie。 它看起来像我从服务器得到一个有效的cookie,但当我发送一个请求到最终的URL与看似有效的cookie时,我应该在响应中获得一些XML的行,但响应是空白的,因为cookie是错误的或因为会话已关闭或其他问题而无效,这是我无法弄清楚的。 服务器发出的cookie在会话结束时到期。在Java中使用HTTP请求发送cookie

在我看来,cookie是有效的,因为当我在Firefox中进行相同的调用时,一个类似的cookie具有相同的名称,并以3首相同的字母和相同长度开始,并存储在Firefox中,会议结束。 如果我然后请求最后的url只有这个特定的cookie存储在firefox(删除所有其他的cookie),xml很好地呈现在页面上。

有关我在这段代码中做错了的任何想法? 另一件事,当我使用这段代码中生成并存储在Firefox中的非常类似的cookie中的值时,最后的请求在HTTP响应中确实给出了XML反馈。

// 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

有没有想过只是切换到普通的http客户端? http://hc.apache.org/httpclient-3.x/ – leonm 2010-03-27 10:49:44

+1

看起来你正在手动完成这一切。我不知道你如何管理会话过期。如果你把所有的服务器代码放在一个servlet中,它会容易得多。这是一个选项吗? – John 2010-03-27 10:56:55

我感觉有点懒得调试代码,但你可能会考虑让一个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;如果你想要每个线程的客户端会话或其他一些更复杂的事务处理,你最好坚持使用手动方法。