简体   繁体   中英

HttpUrlConnection Cookies

My Code is just working fine, but the server responds with 2 Set-Cookies. The problem is that the Session-ID is in the first one and the getHeaderField("Set-Cookie") only returns the last Set-Cookie. How can i get the first one ? Here is a picture of what i mean:

http://www.pic-upload.de/view-22334619/Unbenannt.png.html

import java.awt.BufferCapabilities;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.net.URLEncoder;
import java.util.List;
import java.util.Scanner;

import javax.net.ssl.HttpsURLConnection;

import org.omg.CORBA.portable.OutputStream;

public class main {
public static void main(String[] args) throws IOException {
CookieHandler.setDefault(new CookieManager());
String rawData = "";
String type = "application/x-www-form-urlencoded";
URL u = new URL("http://speed.die-kreuzzuege.de/index.php?action=login&user=USERNAME&pw=PW&antibot=&guest=&check=");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
java.io.OutputStream os = conn.getOutputStream();

String cookie = conn.getHeaderField("Set-Cookie");
    if (cookie != null)
           System.out.println("cookie: " + cookie)
}
}

Try using getHeaderFields() . It returns a Map<String, List<String>> so you can get a List of the headers values:

    for(String cookie : conn.getHeaderFields().get("Set-Cookie")){
        System.out.println("cookie: " + cookie);
    }

Hope it helps.

My code

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

            String cookie = con.getHeaderField("Set-Cookie");
            SharedPreferences.Editor editor = mSettings.edit();
            editor.putString(APP_PREFERENCES_COOKIE, cookie);
            editor.apply();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM