在通过 POST 请求发送用户凭据后,我试图从网站获取 cookie,但它似乎在 android 中无法以这种方式工作。¿ 我是在做坏事吗?请帮忙。我在不同的帖子中搜索过这里,但没有有用的答案。
奇怪的是,它在桌面 Java 实现中运行它完美无缺,但它在 Android 平台上崩溃。并且是完全相同的代码,特别是在调用 HttpURLConnection.getHeaderFields() 时,其他成员方法也会发生这种情况。这是一个简单的代码,我不知道为什么它不起作用。
桌面代码:这只是在 main()
HttpURLConnection connection = null;
OutputStream out = null;
try {
URL url = new URL("http://www.XXXXXXXX.php");
String charset = "UTF-8";
String postback = "1";
String user = "XXXXXXXXX";
String password = "XXXXXXXX";
String rememberme = "on";
String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s"
, URLEncoder.encode(postback, charset)
, URLEncoder.encode(user,charset)
, URLEncoder.encode(password, charset)
, URLEncoder.encode(rememberme, charset));
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", charset);
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(query.length());
out = connection.getOutputStream ();
out.write(query.getBytes(charset));
if (connection.getHeaderFields() == null){
System.out.println("Header null");
}else{
for (String cookie: connection.getHeaderFields().get("Set-Cookie")){
System.out.println(cookie.split(";", 2)[0]);
}
}
} catch (IOException e){
e.printStackTrace();
} finally {
try { out.close();} catch (IOException e) { e.printStackTrace();}
connection.disconnect();
}
所以输出是:
login_key=20ad8177db4eca3f057c14a64bafc2c9
FASID=cabf20cc471fcacacdc7dc7e83768880
track=30c8183e4ebbe8b3a57b583166326c77
client-data=%7B%22ism%22%3Afalse%2C%22showm%22%3Afalse%2C%22ts%22%3A1349189669%7D
ANDROID 代码:这进入 doInBackground AsyncTask 主体
HttpURLConnection connection = null;
OutputStream out = null;
try {
URL url = new URL("http://www.XXXXXXXXXXXXXX.php");
String charset = "UTF-8";
String postback = "1";
String user = "XXXXXXXXX";
String password = "XXXXXXXX";
String rememberme = "on";
String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s"
, URLEncoder.encode(postback, charset)
, URLEncoder.encode(user,charset)
, URLEncoder.encode(password, charset)
, URLEncoder.encode(rememberme, charset));
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", charset);
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(query.length());
out = connection.getOutputStream ();
out.write(query.getBytes(charset));
if (connection.getHeaderFields() == null){
Log.v(TAG, "Header null");
}else{
for (String cookie: connection.getHeaderFields().get("Set-Cookie")){
Log.v(TAG, cookie.split(";", 2)[0]);
}
}
} catch (IOException e){
e.printStackTrace();
} finally {
try { out.close();} catch (IOException e) { e.printStackTrace();}
connection.disconnect();
}
而且这里没有输出,似乎connection.getHeaderFields() 没有返回结果。显示日志至少需要 30 秒:
10-02 16:56:25.918: V/class com.giorgi.myproject.activities.HomeActivity(2596): Header null
在 GALAXY NEXUS 上测试