我想从我的Android应用程序向HTTP服务器发送两个连续的HTTP请求,第一个请求是登录,第二个请求是在成功登录时检索XML数据。我尝试了下面这段代码。
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost1 = new HttpPost(url); //post for login
HttpPost httpPost2 = new HttpPost(url); //post for xml data
// Building post parameters, key and value pair
List<NameValuePair> nameValuePair1 = new ArrayList<NameValuePair>(3);
nameValuePair1.add(new BasicNameValuePair("action", "login"));
nameValuePair1.add(new BasicNameValuePair("username", "admin"));
nameValuePair1.add(new BasicNameValuePair("secret", "admin"));
// Building post parameters, key and value pair
List<NameValuePair> nameValuePair2 = new ArrayList<NameValuePair>(1);
nameValuePair2.add(new BasicNameValuePair("action", "sippeers"));
try {
httpPost1.setEntity(new UrlEncodedFormEntity(nameValuePair1));
httpPost2.setEntity(new UrlEncodedFormEntity(nameValuePair2));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
try {
//executing first http post
HttpResponse httpResponse1 = httpClient.execute(httpPost1);
//executing second http post
HttpResponse httpResponse2 = httpClient.execute(httpPost2);
HttpEntity httpEntity2 = httpResponse2.getEntity();
xml = EntityUtils.toString(httpEntity2);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return xml;
}
我想首先执行 httpPost1 ,然后在连续登录后我想从第二个HttpPost请求中检索字符串 xml 。执行上面的代码时,我收到错误 Permission Denied 。我想我必须在发送两个HttpPost请求时保持某种会话,并且只有在成功执行第一个请求时才应发送第二个HttpPost请求。 如果有人可以指导我解决这个问题,那将非常感激。
答案 0 :(得分:0)
我的意见是,您将登录数据保存在cookie中。 &#34;&#34;&#34; https://hc.apache.org/httpclient-3.x/cookies.html&#34;&#34;&#34;本文介绍如何设置cookie http请求。