Mainly set the HTTP Header
Set in hostconfiguration. setproxy. The following code is used:
Import java. Io. ioexception;
Import java. util. arraylist;
Import java. util. List;
Import org. Apache. commons. httpclient. defaulthttpmethodretryhandler;
Import org. Apache. commons. httpclient. header;
Import org. Apache. commons. httpclient. httpclient;
Import org. Apache. commons. httpclient. httpexception;
Import org. Apache. commons. httpclient. httpstatus;
Import org. Apache. commons. httpclient. usernamepasswordcredentials;
Import org. Apache. commons. httpclient. Auth. authscope;
Import org. Apache. commons. httpclient. Methods. getmethod;
Import org. Apache. commons. httpclient. Params. httpmethodparams;
Public class httpclientuse {
Public static void main (string [] ARGs) throws httpexception, ioexception {
Httpclient = new httpclient ();
Httpclient. gethostconfiguration (). setproxy ("localhost", 808 );
/* // Verification required
Usernamepasswordcredentials creds = new usernamepasswordcredentials ("chenlb", "123456 ");
Httpclient. getstate (). setproxycredentials (authscope. Any, creds );
*/
// Set the HTTP Header
List Headers. Add (new header ("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1 )"));
Httpclient. gethostconfiguration (). getparams (). setparameter ("HTTP. Default-headers", headers );
Getmethod method = new getmethod ("http://www.baidu.com ");
Method. getparams (). setparameter (httpmethodparams. retry_handler,
New defaulthttpmethodretryhandler (3, false ));
Try {
Int statuscode = httpclient.exe cutemethod (method );
If (statuscode! = Httpstatus. SC _ OK ){
System. Out. println ("method failed code =" + statuscode + ":" + method. getstatusline ());
} Else {
System. Out. println (new string (method. getresponsebody (), "gb2312 "));
}
} Finally {
Method. releaseconnection ();
}
}
}
If you want to verify the user name and password, remove the/**/comment. Make the verification valid.
Verification:
Usernamepasswordcredentials creds = new usernamepasswordcredentials ("chenlb", "123456 ");
Httpclient. getstate (). setproxycredentials (authscope. Any, creds );
Set the HTTP request header.
List Headers. Add (new header ("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1 )"));
Httpclient. gethostconfiguration (). getparams (). setparameter ("HTTP. Default-headers", headers );