在myeclipse下新建一个web工程,取名url。在WebRoot下新建一个welcome.jsp.其body标签内的代码为:
name=<%=request.getParameter("name") %>
pass=<%=request.getParameter("pass") %>
在src下建包,写类URLConnectionSendPostRequest,代码如下;
public class URLConnectionSendPostRequest {
public static void main(String[] args) throws Exception {
String s=sendPost("http://localhost:8080/url/welcome.jsp","name=tom&pass=1234");
System.out.println(s);
}
public static String sendPost(String url,String param) throws Exception{
String result="";
URL realURL=new URL(url);
URLConnection conn=realURL.openConnection();
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setDoInput(true);
conn.setDoOutput(true);
PrintWriter out=new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
BufferedReader br=
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line=null;
while((line=br.readLine())!=null){
result+=line+"\n";
}
br.close();
return result;
}
}
运行这个类,在控制台打印了服务器的响应的jsp源码,可以看到服务器拿到了用户名name和密码pass。