https Session and posting problem

前端 未结 1 1572
抹茶落季
抹茶落季 2020-12-14 13:40

I have an application that needs to be able to post to https with an authentication request and then a register request. Currently i am able to post my authentication reques

相关标签:
1条回答
  • 2020-12-14 14:28

    It sounds like you probably need to handle cookie headers to preserve the session. If that's the case this isn't specific to HTTPS. You'll need to find the Set-Cookie response header when you make the first request. Then every request after that you'll pass those through a Cookie request header. Here's a basic example that you can adapt for your case:

    // your first request that does the authentication
    URL authUrl = new URL("https://example.com/authentication");
    HttpsURLConnection authCon = (HttpsURLConnection) authUrl.openConnection();
    authCon.connect();
    
    // temporary to build request cookie header
    StringBuilder sb = new StringBuilder();
    
    // find the cookies in the response header from the first request
    List<String> cookies = authCon.getHeaderFields().get("Set-Cookie");
    if (cookies != null) {
        for (String cookie : cookies) {
            if (sb.length() > 0) {
                sb.append("; ");
            }
    
            // only want the first part of the cookie header that has the value
            String value = cookie.split(";")[0];
            sb.append(value);
        }
    }
    
    // build request cookie header to send on all subsequent requests
    String cookieHeader = sb.toString();
    
    // with the cookie header your session should be preserved
    URL regUrl = new URL("https://example.com/register");
    HttpsURLConnection regCon = (HttpsURLConnection) regUrl.openConnection();
    regCon.setRequestProperty("Cookie", cookieHeader);
    regCon.connect();
    
    0 讨论(0)
提交回复
热议问题