Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Sending a post request with HtmlUnit

Tags:

java

htmlunit

Can't really find any help on this but I've been trying to send a post request with HtmlUnit. The code I have is:

final WebClient webClient = new WebClient();

// Instead of requesting the page directly we create a WebRequestSettings object
WebRequest requestSettings = new WebRequest(
  new URL("www.URLHERE.com"), HttpMethod.POST);

// Then we set the request parameters
requestSettings.setRequestParameters(new ArrayList());
requestSettings.getRequestParameters().add(new NameValuePair("name", "value"));
// Finally, we can get the page
HtmlPage page = webClient.getPage(requestSettings);

Is there an easier way I could carry out a POST request?

like image 521
Joe Taylor Avatar asked Jun 06 '15 21:06

Joe Taylor


1 Answers

This is how it's done

public void post() throws Exception
{

    URL url = new URL("YOURURL");
    WebRequest requestSettings = new WebRequest(url, HttpMethod.POST);

    requestSettings.setAdditionalHeader("Accept", "*/*");
    requestSettings.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    requestSettings.setAdditionalHeader("Referer", "REFURLHERE");
    requestSettings.setAdditionalHeader("Accept-Language", "en-US,en;q=0.8");
    requestSettings.setAdditionalHeader("Accept-Encoding", "gzip,deflate,sdch");
    requestSettings.setAdditionalHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
    requestSettings.setAdditionalHeader("X-Requested-With", "XMLHttpRequest");
    requestSettings.setAdditionalHeader("Cache-Control", "no-cache");
    requestSettings.setAdditionalHeader("Pragma", "no-cache");
    requestSettings.setAdditionalHeader("Origin", "https://YOURHOST");

    requestSettings.setRequestBody("REQUESTBODY");

    Page redirectPage = webClient.getPage(requestSettings);
}

You can customize it however you want. Add/remove headers, add/remove request body, etc ...

like image 189
Arya Avatar answered Sep 19 '22 20:09

Arya