How to set Cookies at Http Get method using Java

前端 未结 3 1578
青春惊慌失措
青春惊慌失措 2020-12-01 16:09

I want to do a manual GET with cookies in order to download and parse a web page. I need to extract the security token, in order to make a post at the forum. I have complete

3条回答
  •  情书的邮戳
    2020-12-01 17:08

    // Grab Set-Cookie headers:
    List cookies = connection.getHeaderFields().get("Set-Cookie");
    
    // ...
    
    // Send them back in subsequent requests:
    for (String cookie : cookies) {
        connection.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
    }
    

    Above code will work for sending multiple cookies just use setRequestProperty instead of addRequestProperty. The working code is:

    // Grab Set-Cookie headers:
    List cookies = connection.getHeaderFields().get("Set-Cookie");
    
    // ...
    
    // Send them back in subsequent requests:
    for (String cookie : cookies) {
        connection.setRequestProperty("Cookie", cookie.split(";", 1)[0]);
    }
    

提交回复
热议问题