The httpclient-4.x.x version was upgraded, a little different from 3. x. x. The following describes how to use the get and post methods to send HTTP requests.
Run the Code directly. The get method is as follows:
Closeablehttpclient httpclient = httpclientbuilder. Create (). Build ();
// Connecttimeout: timeout time for establishing a connection; sockettimeout: Waiting for data time after the socket establishes a connection;
Requestconfig = requestconfig. Custom (). setconnectionrequesttimeout (100). setconnecttimeout (100)
. Setsockettimeout (100). Build ();
Httpresponse = NULL;
Try {
Httpget = new httpget ("http://www.mysite.com ");
// Add head method 1
Httpget. addheader ("User-Agent ",
"Mozilla/5.0 (Windows NT 6.1; wow64) applewebkit/537.36 (khtml, like gecko) Chrome/34.0.1847.131 Safari/537.36 ");
// Method 2
Httpget. addheader (New basicheader ("Accept-language", "ZH-CN, ZH; q = 0.8 "));
Httpget. setconfig (requestconfig );
Httpresponse = httpclient.exe cute (httpget );
String html = entityutils. tostring (httpresponse. getentity (), "GBK ");
System. Out. println (HTML );
} Catch (clientprotocolexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
The following is the POST method. If the parameter setting method is the same as the get method, the details are supplemented:
Closeablehttpclient httpclient = httpclientbuilder. Create (). Build ();
// Connecttimeout: timeout time for establishing a connection; sockettimeout: Waiting for data time after the socket establishes a connection;
Requestconfig = requestconfig. Custom (). setconnectionrequesttimeout (100). setconnecttimeout (100)
. Setsockettimeout (100). Build ();
List <namevaluepair> List = new arraylist <namevaluepair> ();
List. Add (New basicnamevaluepair ("key", "value "));
Httpentity httpentiry = NULL;
Httpresponse = NULL;
Try {
Httpentiry = new urlencodedformentity (list );
} Catch (unsupportedencodingexception e ){
E. printstacktrace ();
}
Httppost = new httppost ("http://www.mysite.com ");
Httppost. setentity (httpentiry );
Httppost. setconfig (requestconfig );
Try {
Httpresponse = httpclient.exe cute (httppost );
System. Out. println (entityutils. tostring (httpresponse. getentity (), "GBK "));
} Catch (clientprotocolexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Some tips:
When you access a webpage, the webpage may return some cookie information, and the httpclient will be automatically set in the object. For example, when simulating login, first request the login page using get method, so that httpclient will maintain some cookie information, and then use POST method with parameters to simulate login, succeeded; if the GET request login page is omitted and post is executed directly, the request fails. Therefore, you need to keep the httpclient object for further operations. You can use poolinghttpclientconnectionmanager to manage httpclient.
Use httpclient 4.x