如何用java程序以post方式发送表单参数给服务器?
大家做过类似的东西吗?初来乍到,望兄弟们给予一些帮助,3x.
我想达到的效果是:
不用jsp,而是用一段java程序(MyJavaPost.java),通过post方式提交两个参数的值,请求服务器的http://localhost:8090/test/test.jsp,并收到服务器的响应。
test.jsp内容如下:
<%
String param1 = request.getParameter( "param1 ");
String param2 = request.getParameter( "param2 ");
out.print( " <br> param1= " + param1);
out.print( " <br> param2= " + param2);
%>
请问
MyJavaPost.java
应该如何写?
------解决方案--------------------String url = "http://www.newsmth.net/bbslogin2.php ";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair( "id ", "youUserName "),
new NameValuePair( "passwd ", "yourPwd ") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader( "location ");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println( "The page was redirected to: " + location);
} else {
System.err.println( "Location field value is null. ");
}
return;
}