【发布时间】:2010-06-30 19:32:22
【问题描述】:
我有一个用户名作为密码,我需要将其作为 android 应用程序的一部分发送到网站(是的,它是 https),一旦通过 POST 提交给服务器,服务器应该返回 cookie。我需要能够捕获这些 cookie,并允许在我设置的 web 视图中访问它们。
我该怎么做?
谢谢
【问题讨论】:
我有一个用户名作为密码,我需要将其作为 android 应用程序的一部分发送到网站(是的,它是 https),一旦通过 POST 提交给服务器,服务器应该返回 cookie。我需要能够捕获这些 cookie,并允许在我设置的 web 视图中访问它们。
我该怎么做?
谢谢
【问题讨论】:
您可以在 CookieManager 实例上调用setCookie function,您可以通过在其上调用名为 getInstance 的静态方法来获取该实例。
【讨论】:
一般来说,在Java HttpURLConnection 中你可以这样设置/获取cookie(这里是整个连接过程):
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set cookie. sCookie is my static cookie string
if(sCookie!=null && sCookie.length()>0){
conn.setRequestProperty("Cookie", sCookie);
}
// Send data
OutputStream os = conn.getOutputStream();
os.write(mData.getBytes());
os.flush();
os.close();
// Get the response!
int httpResponseCode = conn.getResponseCode();
if (httpResponseCode != HttpURLConnection.HTTP_OK){
throw new Exception("HTTP response code: "+httpResponseCode);
}
// Get the data and pass them to the XML parser
InputStream inputStream = conn.getInputStream();
Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);
inputStream.close();
//Get the cookie
String cookie = conn.getHeaderField("set-cookie");
if(cookie!=null && cookie.length()>0){
sCookie = cookie;
}
/* many cookies handling:
String responseHeaderName = null;
for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
if (responseHeaderName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
}
}*/
conn.disconnect();
【讨论】: