【发布时间】:2024-04-30 22:30:03
【问题描述】:
我目前正在尝试使用 cookie(没有成功),我可以很好地获得它的价值,但将其寄回则是完全不同的故事。
我正在使用两个 AsyncTask 类、两个按钮和两个文本框。单击第一个按钮后,第一个类访问 URL 并获取将其作为字符串值保存到第一个文本框中的 cookie(工作正常)。 然而,第二次点击应该从文本框中获取 cookie 并将其发送回第二个 URL 以显示在线消息(不起作用)。
两个按钮的代码:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//executing the first AsynTask
new DownloadWebpageTask().execute(FirstLink);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] ar= new String[2];
//save the value of the second link and the cookie value in an array
ar[0]=SecondLink;
ar[1]= String.valueOf(textBox1.getText());
//executing the second AsynTask
new showC().execute(ar);
}
});
异步任务:
//First AsyncTask
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
URL url = null;
URLConnection conn=null;
String output="";
try {
url = new URL(urls[0]);
conn = url.openConnection();
conn.connect();
return conn.getHeaderField("Set-Cookie");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Error";
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
//store the cookie value as string, something like : PHPSESSID=....;
textBox1.setText(result);
}
}
//Second AsyncTask
private class showC extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
URL url = null;
HttpURLConnection conn=null;
String output="";
try {
url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Set-Cookie", urls[1]);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
output=br.readLine();
return output+" "+conn.getHeaderField("Set-Cookie");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Error";
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
text2.setText(result);
}
}
//----------------------
在第二个链接中设置 cookie 值不起作用,并且仅在再次检查它的值时返回不同的 cookie。应该注意,在 Android 中使用 cookie 的文档非常少,并且大多数文档都是基于使用已弃用的 HttpClient 而不是UrlConnection,我的技术也是基于example.
【问题讨论】:
标签: android cookies httpurlconnection