如何从 Java 中的 post 请求中提取 httponly cookie?

How to extract httponly cookie from a post request in Java?

我有以下 cURL 请求

curl -i --data 'user=user1&password=password1' -X POST http://127.0.0.1:8080/login

这 returns 我的以下回复:

    HTTP/1.1 200 OK
    Access-Control-Allow-Origin:
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Headers: authorization,Content-Type
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, HEAD, DELETE
    Date: Monday, January 22, 2017 10:07:22 AM UTC
    Set-Cookie: JSESSIONID=XXXYYYZZZ; Path=/; HttpOnly
    Content-Type: application/json
    Content-Length: 118
    Server: Jetty(9.2.15.v20160210)
    {"status":"OK","message":"","body":{"principal":"user1","ticket":"el23-esedejhz943"}}

我想在 Java 中进行此调用,并提取 Set-Cookie 字段中的 JSESSIONID。我怎样才能做到这一点?

    import java.net.URL;
    import java.net.URLConnection;
    import java.util.List;
    import java.util.Map;

    public class ResponseHeaderUtil {

      public static void main(String[] args) {

        try {

        URL obj = new URL("http://127.0.0.1:8080/login");
        URLConnection conn = obj.openConnection();
    //add reuqest header 

            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
            String urlParameters = "user=user1&password=password1";
            Map<String, List<String>> map = conn.getHeaderFields();

        System.out.println("Printing Response Header...\n");

        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey()
                               + " ,Value : " + entry.getValue());
        }

        System.out.println("\nGet Response Header By Key ...\n");
        String server = conn.getHeaderField("Server");

        if (server == null) {
            System.out.println("Key 'Server' is not found!");
        } else {
            System.out.println("Server - " + server);
        }

        System.out.println("\n Done");

        } catch (Exception e) {
        e.printStackTrace();
        }

      }
    }

实现这一目标的最佳方法之一是像这样使用名为 HtmlUnit 的库:

public void post() throws Exception

    {

        URL url = new URL("http://127.0.0.1:8080/login");
        WebRequest requestSettings = new WebRequest(url, HttpMethod.POST);
        requestSettings.setRequestParameters(new ArrayList());
        requestSettings.getRequestParameters().add(new NameValuePair("user", "user1"));
        requestSettings.getRequestParameters().add(new NameValuePair("password", "password1"));
        WebClient webClient = new WebClient();
        Page redirectPage = webClient.getPage(requestSettings);
        // here is your jSessionId cookie:
        Cookie jSessionId = webClient.getCookieManager().getCookie("JSESSIONID")

    }

您可以做得更好,例如,以编程方式转到登录页面,然后在密码字段中输入密码,在用户名字段中输入用户名(使用 select 或又名 jQuery 到 select 字段),然后获取表单,提交它,然后读取 cookie。阅读 HtmlUnit 文档以获取更多信息 - 它真的很棒。

一种不使用任何外部库的方法,适用于 http,但不适用于 https(因为证书 - 这可以设置为工作,但对于这个 post 来说太宽泛了)

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JsessionIdExtractor {

    public static void main(String[] args) throws Exception {
        String jSessionId = logInAndRetrieveJsessionId();
        System.out.println("JSESSIONID is: " + jSessionId);
    }

    private static String logInAndRetrieveJsessionId() throws Exception {
        String url = "http://127.0.0.1:8080/login";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Some browser name eg. fierfox");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        String postParameters = "user=user1&password=password1";
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParameters);
        System.out.println("Response Code : " + responseCode);
        return extractJsessionId(con);
    }

    private static String extractJsessionId(HttpURLConnection con) {
        Map<String, List<String>> headerFields = con.getHeaderFields();
        Set<String> headerFieldsSet = headerFields.keySet();
        Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
        while (hearerFieldsIter.hasNext()) {
            String headerFieldKey = hearerFieldsIter.next();
            if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
                List<String> headerFieldValue = headerFields.get(headerFieldKey);
                for (String headerValue : headerFieldValue) {
                    System.out.println("Cookie Found...");
                    String[] fields = headerValue.split(";\s*");
                    String cookieValue = fields[0];
                    if (cookieValue.toUpperCase().trim().startsWith("JSESSIONID")) {
                        return cookieValue.split("=")[1];
                    }
                }
            }
        }
        throw new RuntimeException("there is no JSESSIONID cookie in reponse");
    }
}