0

我目前正在尝试使用 HttpURLConnection 登录,然后获取会话 cookie...

我已经在我自己的服务器上的一些测试页面上尝试过,并且效果很好。当我发送时,a=3&b=5我得到8了 cookie(PHP 页面将两者加在一起)!但是当我在另一个页面上尝试时,输出只是页面,就好像我没有用 POST 发送任何内容:(

欢迎提出一般性的改进建议!:)

我的代码:

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 + "\"");
4

1 回答 1

0

cookie 路径最初应设置为; Path=/,还需要在 POST 的请求标头中设置一个 Set-Cookie。

最好用HttpClient重写它。

于 2012-12-26T16:58:50.837 回答