JAVA模拟post请求

时间:2021-01-17 16:57:31

在存在form的场合下,我们可以模拟post请求,从而达到想要的效果。

但是,在某些场合下面,我们不想创建多个的form表单,而又想实现post请求,接下来,总结下解决办法。

post请求:

public String makeHtmlPageGet(String url, String[] parameters) throws Exception {

StringBuffer sbRtn = new StringBuffer();
sbRtn.append("<html>");
sbRtn.append("<head>");
sbRtn.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
sbRtn.append("<title>登录中</title>");
sbRtn.append("</head>");
sbRtn.append(
"<form id=\"postsubmit\" name=\"postsubmit\" action=\"")
.append(url).append("\" method=\"post\">");

for(int i=0;i<parameters.length;i++){
String[] keyAndValue = parameters[i].split("=");
if(keyAndValue.length == 2){
sbRtn.append("<input type=\"hidden\" name=\"").append(keyAndValue[0])
.append("\" value=\"").append(keyAndValue[1])
.append("\"/>");
}else{
sbRtn.append("<input type=\"hidden\" name=\"").append(keyAndValue[0])
.append("\" value=\"\"/>");
}

}
// submit按钮控件请不要含有name属性
sbRtn.append("</form>");
sbRtn.append("<script>document.forms['postsubmit'].submit();</script>");
sbRtn.append("</html>");
return sbRtn.toString();
}
<pre name="code" class="java">模拟一个页面,将需要post请求的参数进行拼接,通过js的submit提交进行post请求。

 
//生成post请求页面
result = makeHtmlPageGet(url, parameters);

PrintWriter out = response.getWriter();
out.println(new String(result.getBytes("UTF-8"),"ISO-8859-1"));
解决post请求的需求。