`

HttpClient Access to HTML Form

阅读更多

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();

 

 Reference:http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/

  • lib.rar (682.6 KB)
  • 下载次数: 4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics