java模拟页面表单登录
简单的通过表单的post请求提交到后台
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package testpostlogin; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import java.util.StringTokenizer; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class TestPost { public static void main(String args[]) throws IOException{ Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名:"); String user_name = scanner.next(); System.out.println("请输入密码:"); String password = scanner.next(); testPost(user_name , password); } public static void testPost(String user_name , String password) throws IOException{ String login =""; //URL newURL = new URL("http://passport.mop.com/login?method=post"); URL newURL = new URL("http://localhost:8080/SSM/loginName.mvc?method=post"); HttpURLConnection conn = (HttpURLConnection) newURL.openConnection(); conn.setRequestProperty("Connection","keep-alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),"utf-8"); //login =login+"loginName="+user_name+"&"+"loginPasswd="+password; out.write("name="+user_name+"&password="+password); out.flush(); out.close(); Date date=new Date(); SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); String random1=sdf1.format(date); String random=sdf.format(date); String path="F:\\postget\\"+random1+"\\"+random+".txt"; File file = new File(path); // 如果路径不存在,则创建 if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } //判断文件是否存在,不存在就创建文件 if(!file.exists()&& !file .isDirectory()) { file.createNewFile(); } InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); FileOutputStream fis=new FileOutputStream(file); String line; //将登陆后的页面元素读取并保存到文件中 while ((line = reader.readLine()) != null) { fis.write(line.getBytes()); System.out.println(line); } reader.close(); } }