论坛首页 编程语言技术论坛

HttpClient Access HTML Form

浏览 1617 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-03-19  

Sample Html Form Code:

<s:form action="Add" method="post">
		<s:textfield label="ISBN" name="book.isbn"></s:textfield>
		<s:textfield label="Name" name="book.name"></s:textfield>
		<s:textfield label="Price" name="book.price"></s:textfield>
		<s:submit></s:submit>
</s:form>

 

Java Access html form through HttpClient Code:

public static void form() {
		HttpClient httpClient = new DefaultHttpClient();
		try {
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("book.isbn", "753-95487621"));
			formparams.add(new BasicNameValuePair("book.name", "HttpClient"));
			formparams.add(new BasicNameValuePair("book.price", "45.6"));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
					"UTF-8");
			HttpPost httpPost = new HttpPost(
					"http://localhost:8080/struts2/book/Add.action");
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			System.out.println("Add form get: " + response.getStatusLine());
			EntityUtils.consume(entity);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
			System.out.println("ok");
		}
	}

 

main method:

form();

 

Then ,you can do what you want to ,of course ,Please do not do the illegal things。

  • lib.rar (682.6 KB)
  • 下载次数: 4
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics