I would like to submit a form programmatically in android. I don't want any user interaction with a web browser. The user will provide inputs in an EditField and then the inputs will be submitted Through http post method via HTTPwebmethod. But I didn't get any success in the same. Please advise. I have used HTMLUnit in java but its not working in android.
final WebClient webClient = new WebClient();
final HtmlPage page1 = webClient.getPage("http://www.mail.example.com");
final HtmlForm form = page1.getHtmlElementById("loginform");
final HtmlSubmitInput button = form.getInputByName("btrn");
final HtmlTextInput textField1 = form.getElementById("user");
final HtmlPasswordInput textField2 = form.getElementById("password");textField1.setValueAttribute("user.name");
textField2.setValueAttribute("pass.word"); final HtmlPage page2 = button.click();
Oops. Sorry. Looks like you are trying to POST through the browser afterall.
Here's a snippet I've been using to accomplish HTTP POST's in Android without going through the web browser:
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name1", "value1"));
nameValuePairs.add(new BasicNameValuePair("name2", "value2"));
nameValuePairs.add(new BasicNameValuePair("name3", "value3"));
// etc...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
I think that should work for what you're trying to do. I have TIMEOUT_MS set to 10000 (so, 10 seconds)
Then you can read out the server's response using something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With