简体   繁体   中英

Sending a POST request with multiple keywords as parameters using HTMLUnit

I am sending a POST request using HTMLUnit that sends keywords as parameters. An example of the URL is:

website.com/foo/bar/api?keywords=word1,word2,word3&language=en

The problem is my application is dynamically picking these words and the amount of words can go up to 10 or 20 or even more. How do you append a Set of words as values to a HTTP request. My code at the moment is:

requestSettings = new WebRequest(new URL("website.com/foo/bar/api?"),
                        HttpMethod.POST);
                Iterator<String> itr = list.iterator();
                while(itr.hasNext()) {
                    requestSettings.getRequestParameters()
                            .add(new NameValuePair("keywords[]", itr.next()));
                }
                requestSettings.getRequestParameters().add(new NameValuePair("language", "en"));
                System.out.println(requestSettings.getUrl().toString());
                response = webClient.getPage(requestSettings).getWebResponse();

This code does not return a valid respone. What am I doing wrong here?

Give this a try:

using (var client = new WebClient())
{
     var dataObject = new {
         KeyWords = "one, two, three"
     };

     var serializer = new JavaScriptSerializer();
     var json = serializer.Serialize(dataObject);

     var response = client.UploadString("yourUrl", json);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM