循环HttpPost请求

时间:2011-07-19 16:57:16

标签: android http

我需要使用几个不同的帖子请求来访问网页中的数据。现在我用:

HttpClient httpclient = new DefaultHttpClient();  
HttpPost httppost = new HttpPost("https://myurl");  
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
nameValuePairs.add(new BasicNameValuePair("action", "search"));  
nameValuePairs.add(new BasicNameValuePair("ndc", ndc));  
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
HttpResponse response = httpclient.execute(httppost);

我需要使用变量ndc的不同值发送此请求。循环这条线是个好主意吗?如果是这样,如何重用HttpClient和HttpPost变量?

1 个答案:

答案 0 :(得分:0)

如果URL需要保持不变,那么您应该只更改需要发送的值。

for (int i=0; i<ndcArray.length;i++)
{

    if(i==theNumberWhenURLhasToBeChanged)  //adjust this condition based on your    knowledge when the url has to be changed, lets say if i > theNumberWhenURLhasToBeChanged, then change the url...
  {
  httppost = new HttpPost(URLs[theNumberWhenURLhasToBeChanged]);
  }  

nameValuePairs.add(new BasicNameValuePair("ndc", ndcArray[i]));  
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
HttpResponse response = httpclient.execute(httppost);
}

请注意:响应每次都会更改,因此请记住,您应该在某处保存响应。并且ndcArray []可以替换为您想要的任何结构。