我想从我的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。在执行上述代码时,我得到的错误说权限被拒绝。我认为我必须在发送两个HttpPost请求时保持某种会话,并且应该仅在成功执行第一个请求时发送第二个HttpPost请求。如果有人能指导我解决这个问题,我将不胜感激。
我的意见是,您将登录数据保存在cookie中。