我想在 android 中以编程方式提交表单。我不希望任何用户与网络浏览器进行交互。用户将在 EditField 中提供输入,然后输入将通过 HTTPweb 方法通过 http post 方法提交。但我没有取得任何成功。请指教。我在 java 中使用过 HTMLUnit,但它在 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();
最佳答案
糟糕。对不起。看起来你毕竟试图通过浏览器发布。
这是我一直用来在 Android 中完成 HTTP POST 而无需通过网络浏览器的 fragment :
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);
我认为这应该适用于您正在尝试做的事情。我将 TIMEOUT_MS 设置为 10000(所以,10 秒)
然后你可以使用类似这样的方式读出服务器的响应:
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
关于android - 在android中以编程方式提交html表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2949810/