Java HttpURLConnection bekommt keine cookies
        Posted  
        
            by 
                TeNNoX
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by TeNNoX
        
        
        
        Published on 2012-12-17T16:41:59Z
        Indexed on 
            2012/12/17
            17:03 UTC
        
        
        Read the original article
        Hit count: 477
        
ich versuche über eine HttpURLConnection einen Login auf einer Webseite durchzuführen, und davon dann die cookies zu erhalten...
Bei meinen Testseiten auf einem eigenen Server geht es problemlos, ich sende "a=3&b=5" und als cookie erhalte ich "8", also die Summe.
Wenn ich dies allerdings auf der gewollten Seite anwende, kommt einfach nur die Seite, als ob ich gar nichts per POST gesendet hätte... :(
Generelle Verbesserungsvorschläge sind auch erwünscht! :)
Mein Code:
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("useragent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0");
conn.setRequestProperty("Connection", "keep-alive");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("USER=tennox&PASS=*****");
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String response = new String();
while ((line = in.readLine()) != null) {
    response = response + line + "\n";
}
in.close();
System.out.println("headers:");
int i = 0;
String header;
while ((header = conn.getHeaderField(i)) != null) {
    String key = conn.getHeaderFieldKey(i);
    System.out.println(((key == null) ? "" : key + ": ") + header);
    i++;
}
String cookies = conn.getHeaderField("Set-Cookie");
System.out.println("\nCookies: \"" + cookies + "\"");
© Stack Overflow or respective owner