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

时间:2017-01-24 05:00:12

标签: java curl post cookies jsessionid

我有以下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。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

一种不使用任何外部库的方法,适用于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");
    }
}

答案 1 :(得分:0)

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

      }
    }

答案 2 :(得分:0)

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

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来选择字段),然后获取表单,提交,然后读饼干。阅读HtmlUnit文档以获取更多信息 - 这是非常棒的库。