This example uses HttpClient 3.0.jar
Package test;
Import Org.apache.commons.httpclient.Cookie;
Import org.apache.commons.httpclient.HttpClient;
Import Org.apache.commons.httpclient.cookie.CookiePolicy;
Import Org.apache.commons.httpclient.NameValuePair;
Import Org.apache.commons.httpclient.methods.GetMethod;
Import Org.apache.commons.httpclient.methods.PostMethod; /** * @author Author: Chenzenan e-mail:chen.ze.nan@163.com * @version Date Created: 2012-8-10 pm 04:35:48 Copyright?
2012-8-10 Shanghai XXX Co. * LTD.
All right reserved. */public class Httpclientlogin {public static void main (string[] args) {//login Url String loginurl = "http://local
Host/login.jsp ";
URL String dataurl = "http://localhost/applyopen/printApprize.jsp?iid=1516" to be accessed after login;
HttpClient httpclient = new HttpClient ();
Analog landing, according to the actual server requirements to select Post or GET request mode Postmethod Postmethod = new Postmethod (loginurl); Set login required information, username and password namevaluepair[] data = {new Namevaluepair ("name", "admin"), New Namevaluepair ("Password", "123 456 ") };
Postmethod.setrequestbody (data); try {//Set HttpClient receive cookies, using the same policy as the browser httpclient.getparams (). Setcookiepolicy (Cookiepolicy.browser_compat
ibility);
Httpclient.executemethod (Postmethod);
Get landed Cookie cookie[] cookies = httpclient.getstate (). GetCookies ();
StringBuffer tmpcookies = new StringBuffer ();
for (Cookie c:cookies) {tmpcookies.append (c.tostring () + ";");
//To perform the operation after landing 1581,1602,1603,1610,1609,1608,1607,1606,1605,1620,1619,1617,1616,1622,1626,1642,1648,1647,1657
GetMethod GetMethod = new GetMethod (Dataurl);
Each access to an authorized URL should be preceded by a cookie as a pass Getmethod.setrequestheader ("cookie", tmpcookies.tostring ()); You can also set more request data via Postmethod/getmethod//For example, where Referer from, UA like search engine table name of who you are, except for the unscrupulous search engine postmethod.setrequestheader (
"Referer", "http://www.cc");
Postmethod.setrequestheader ("user-agent", "www Spot");
Httpclient.executemethod (GetMethod); Print out the return data and verify the success. String Text = Getmethod.getresponsebodyasstRing ();
System.out.println (text);
catch (Exception e) {e.printstacktrace ();
}
}
}