0

I'm currently trying to do a login with HttpURLConnection and then get the session cookies...

I already tried that on some test pages on my own server, and that works perfectly. When i send a=3&b=5 i get 8 as cookie (PHP page adds both together)! But when i try that at the other page, the output is just the page as if I just sent nothing with POST :(

General suggestions for improvement are welcome! :)

My 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 + "\"");
micha
  • 47,774
  • 16
  • 73
  • 80
TeNNoX
  • 1,899
  • 3
  • 16
  • 27

1 Answers1

0

The cookie path should initially be set with ; Path=/, also needing a Set-Cookie in the request header of the POST.

Better rewrite it all with an HttpClient.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Where/how should i set that? And the set-cookie like this? _conn.setRequestProperty("Set-Cookie", "true");_ – TeNNoX Dec 26 '12 at 17:59
  • `conn.setRequestProperty("Cookie","xxx=yyy; Path=/");` see [this](http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests) – Joop Eggen Dec 26 '12 at 18:31
  • Okay, but where do i know xxx and yyy from? – TeNNoX Dec 30 '12 at 15:11
  • In the browser (say Firefox) you can inspect the cookies from the site, and see what to mimick and expect. – Joop Eggen Dec 30 '12 at 18:55
  • Well, look at this page: [link](https://sicherheitsserver.net-build.de/gymbel/schuelerportal/ssl/login.html) There are no cookies before i login, so i send the USER and PASS post data, but i dont get cookies and in the inputstream i get the normal login page... – TeNNoX Dec 31 '12 at 00:04
  • Logging in with false data gives a cookie with name PHPSESSID_netsh10319, value c4637af... for domain sicherheitsserver.net-build.de, path /. I would really give HttpClient a try. I picked a [german https example](http://www.java-forum.org/netzwerkprogrammierung/42886-https-apache-httpclient.html). – Joop Eggen Dec 31 '12 at 11:07