Web login is nothing more than webpage acquisition, cookie management, post and get simulation.
1. webpage Content Retrieval
Java. io. InputStream in;
Java.net. URL url = new java.net. URL (www.xyz.com/content.html );
Java.net. HttpURLConnection connection = (java.net. HttpURLConnection)
Url. openConnection ();
Connection = (java.net. HttpURLConnection) url. openConnection ();
// Simulate it as IE
Connection. setRequestProperty ("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000 )");
Connection. connect ();
In = connection. getInputStream ();
Java. io. BufferedReader breader =
New BufferedReader (new InputStreamReader (in, "GBK "));
String str = breader. readLine ());
While (st! = Null ){
System. out. println (str );
Str = breader. readLine ());
}
2. cookie Management
1. Direct Mode
Get cookie:
HttpURLConnection huc = (HttpURLConnection) url. openConnection (); |
| InputStream is = huc. getInputStream (); |
| String cookieVal = hc. getHeaderField ("Set-Cookie "); |
| SessionId = cookieVal. substring (0, cookieVal. indexOf (";")); |
}
| HttpURLConnection huc = (HttpURLConnection) url. openConnection (); |
| Huc. setRequestProperty ("Cookie", sessionId ); |
| InputStream is = huc. getInputStream (); |
|
2. The jcookie package used (http://jcookie.sourceforge.net /)
Get cookie:
| URL url = new URL ("http://www.site.com /"); |
| HttpURLConnection huc = (HttpURLConnection) url. openConnection (); |
| InputStream is = huc. getInputStream (); |
| Client client = new Client (); |
| CookieJar cj = client. getCookies (huc ); |
The new request uses the cookie obtained above:
| Url = new URL ("http://www.site.com /"); |
| Huc = (HttpURLConnection) url. openConnection (); |
| Client. setCookies (huc, cj ); |
3. post Mode Simulation
URL url = new URL ("www.xyz.com ");
HttpURLConnection huc = (HttpURLConnection) url. openConnection ();
// Set allow output
Huc. setDoOutput (true );
// Set it to post
Huc. setRequestMethod ("POST ");
Huc. setRequestProperty ("User-Agent", "Mozilla/4.7 [en] (Win98; I )");
StringBuffer sb = new StringBuffer ();
Sb. append ("userName =" + userNme );
Sb. append ("& password =" + password );
// Post information
OutputStream OS = huc. getOutputStream ();
OS. write (sb. toString (). getBytes ("GBK "));
OS. close ();
BufferedReader br = new BufferedReader (new InputStreamReader (huc. getInputStream ()))
Huc. connect ();
String line = br. readLine ();
While (line! = Null ){
L
System. out. printli (line );
Line = br. readLine ();
}
Conclusion:
The above code can basically achieve the login and information acquisition functions of the website. When we see the fire of software such as login, let's do it.
Refer:
1. A recipe for cookie management
Http://www.javaworld.com/javaworld/jw-04-2002/jw-0426-cookie.html