This essay records the Get and post requests for httpclient.
Using Maven to build a dependency package, the version I'm using is 4.5.3
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
The code is as follows:
1 Importorg.apache.http.HttpEntity;2 ImportOrg.apache.http.HttpResponse;3 ImportOrg.apache.http.NameValuePair;4 Importorg.apache.http.client.entity.UrlEncodedFormEntity;5 ImportOrg.apache.http.client.methods.HttpGet;6 ImportOrg.apache.http.client.methods.HttpPost;7 Importorg.apache.http.impl.client.CloseableHttpClient;8 Importorg.apache.http.impl.client.HttpClients;9 ImportOrg.apache.http.message.BasicNameValuePair;Ten ImportOrg.apache.http.protocol.HTTP; One Importorg.apache.http.util.EntityUtils; A - Importjava.util.ArrayList; - Importjava.util.List; the ImportJava.util.Map; - - Public classHttpRequest { - Private Static FinalString user_agent = "mozilla/5.0"; + Private Static FinalString TOKEN = "Bearer adad2342dfbcdcb44232bf6a"; - Private Static FinalString content_type = "application/x-www-form-urlencoded";
Send a GET request + Public Staticstring sendget (string url) { AString result = ""; atCloseablehttpclient httpClient =Httpclients.createdefault (); -HttpGet HttpGet =Newhttpget (URL); -Httpget.addheader ("User-agent", user_agent); -Httpget.addheader ("Authorization", TOKEN); - Try{ -HttpResponse response =Httpclient.execute (httpget); inhttpentity entity =response.getentity (); -result =entityutils.tostring (entity); to}Catch(Exception e) { + e.printstacktrace (); - } the returnresult; * } $Send a POST requestPanax Notoginseng Public StaticString Sendpost (String url,map<string,string>Mapparam) { -String result = ""; theCloseablehttpclient httpClient =Httpclients.createdefault (); +HttpPost HttpPost =Newhttppost (URL); AHttppost.setheader ("Content-type", content_type); theHttppost.addheader ("User-agent", user_agent); +Httppost.addheader ("Authorization", TOKEN); - Try{ $ if(Mapparam! =NULL){ $list<namevaluepair> PostData =NewArraylist<namevaluepair>(); - for(map.entry<string,string>Entry:mapParam.entrySet ()) { -Postdata.add (NewBasicnamevaluepair (Entry.getkey (), Entry.getvalue ())); the } -Httppost.setentity (Newurlencodedformentity (PostData, HTTP. Utf_8));Wuyi } theHttpResponse response =Httpclient.execute (httppost); -httpentity entity =response.getentity (); Wuresult =entityutils.tostring (entity); -}Catch(Exception e) { About e.printstacktrace (); $ } - returnresult; - } -}
Get and POST requests for Java learning HttpClient