开发者

Loop HttpPost requests

开发者 https://www.devze.com 2023-03-21 04:27 出处:网络
I need to access data from a webpage using several different post requests. For now I use: HttpClient httpclient = new DefaultHttpClient();

I need to access data from a webpage using several different post requests. For now I use:

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

I need to sent this request using different values for the variable ndc. Would looping this lines be a good idea? If so, how to reuse the HttpClient and HttpPost variables?


If the URL needs to stay the same, then you should only change the values that need to sent.

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);
}

Note that: response will change each time, so bear in mind that you should save the response somewhere. And ndcArray[] can be replaced with any structure you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消