我有一个用户名作为密码我需要发送到网站作为Android应用程序的一部分(是的它是https),并且一旦通过POST提交给服务器,服务器应该返回cookie。我需要能够捕获这些cookie,并允许在我已经建立的webview中访问它们。
我该怎么做?
由于
答案 0 :(得分:1)
你可以在CookieManager实例上调用setCookie function,你可以通过调用名为getInstance的静态方法来获取它。
答案 1 :(得分:1)
通常,在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();