簡體   English   中英

如何從 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

這將返回以下響應:

    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。 我怎樣才能做到這一點?

一種不使用任何外部庫的方法,適用於 http,但不適用於 https(因為證書 - 這可以設置為工作,但對於這篇文章來說太寬泛了)

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");
    }
}
    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")

    }

你可以做得更好,例如,以編程方式進入登錄頁面,然后在密碼字段中輸入密碼,在用戶名字段中輸入用戶名(使用選擇器又名 jQuery 來選擇字段),然后獲取表單,提交它,然后讀取 cookie。 閱讀 HtmlUnit 文檔以獲取更多信息——它真的是一個很棒的庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM