Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit HTML Form in Java

I am trying to fill in a HTML Form, press a submit button of the form and then get the response from it.

Filling in the form works really well but i can't figure out how to press the submit button on the page.

I am using the apache httpclient libraries.

My code is:

        httpclient = new DefaultHttpClient();
        HttpPost httpost = new HttpPost(pUrl);

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("filter_response_time_http", "1"));
        nvps.add(new BasicNameValuePair("filter_port", "80"));
        nvps.add(new BasicNameValuePair("filter_country", "US"));
        nvps.add(new BasicNameValuePair("submit", "Anzeigen"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);


        entity = response.getEntity();

The code for the submit button is:

<input onclick="doSubmit();" id="submit" type="submit" value="Anzeigen" name="submit" /> 
like image 534
Koepasso Avatar asked Oct 08 '22 21:10

Koepasso


2 Answers

You don't "click a button" with HttpClient; all it does is HTTP stuff, which is unrelated to JS and the DOM.

If you want to emulate a browser, use something like JWebUnit, which can drive both HttpClient and Selenium, and provides JavaScript support.

like image 183
Dave Newton Avatar answered Oct 12 '22 11:10

Dave Newton


Your submit button calls a javascript function when clicked. You can't emulate that behaviour using your java code.

For that you need to use a headless browser like htmlunit which can handle javascript.

like image 27
RanRag Avatar answered Oct 12 '22 12:10

RanRag