Java模拟登陆【转载】

 1 import java.io.BufferedReader;   
 2 import java.io.IOException;   
 3 import java.io.InputStream;   
 4 import java.io.InputStreamReader;   
 5 import java.io.OutputStreamWriter;   
 6 import java.net.URL;   
 7 import java.net.URLConnection;   
 8   
 9 public class TestPost {   
10   
11     public static void testPost() throws IOException {   
12   
13         //连接地址
14         String surl = "http://219.238.180.***:80/.../loginservlet?command=login";
15         
16         /**  
17          * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using  
18          *  java.net.URL and //java.net.URLConnection  
19          */  
20         URL url = new URL(surl); 
21         URLConnection connection = url.openConnection(); 
22         
23         /**  
24          * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。  
25          * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:  
26          */  
27         connection.setDoOutput(true);   
28         /**  
29          * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...  
30          */  
31         OutputStreamWriter out = new OutputStreamWriter(connection   
32                 .getOutputStream(), "UTF-8");   
33         out.write("user_account=admin&user_password=******"); //post的关键所在!   
34         // remember to clean up   
35         out.flush();   
36         out.close();   
37         /**  
38          * 这样就可以发送一个看起来象这样的POST:   
39          * POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:  
40          * text/plain Content-type: application/x-www-form-urlencoded  
41          * Content-length: 99 username=bob password=someword  
42          */  
43         // 一旦发送成功,用以下方法就可以得到服务器的回应:   
44         String sCurrentLine;   
45         String sTotalString;   
46         sCurrentLine = "";   
47         sTotalString = "";   
48         InputStream l_urlStream;   
49         l_urlStream = connection.getInputStream();   
50         // 传说中的三层包装阿!   
51         BufferedReader l_reader = new BufferedReader(new InputStreamReader(   
52                 l_urlStream));   
53         while ((sCurrentLine = l_reader.readLine()) != null) {   
54             sTotalString += sCurrentLine + "
";   
55   
56         }   
57         System.out.println(sTotalString);   
58     }   
59   
60     public static void main(String[] args) throws IOException {   
61   
62         testPost();   
63   
64     }   
65   
66 }

以上代码通过测试,能得到登录后的页面静态代码

有兴趣可以自己测试,注意地址是提交的地址,参数也得一致

 原文地址:http://zhoujingxian.iteye.com/blog/439738

原文地址:https://www.cnblogs.com/dekevin/p/3581377.html