PackageCom.xxx.xxx.common;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.util.Map;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.config.RequestConfig;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.impl.client.HttpClientBuilder;ImportOrg.apache.http.HttpResponse;Importcom.google.common.base.Charsets; Public classHttpRequest {/*** A request to send a GET method to a specified URL *@paramURL * URL to send request *@paramparam * HttpRequest request parameters. * @paramheaders * Httpheader parameters to be added *@paramTimeout * Request time-out *@returnresult represents the response of the remote resource*/ Public StaticString Get (string url, string param, map<string, string> headers,intTimeout) {String result= ""; BufferedReader in=NULL; String Requrl= URL + "?" +param; Try { //Constructing HttpRequest SettingsRequestconfig config =Requestconfig.custom (). Setconnecttimeout (timeout). Setconnectionrequesttimeout (timeout). build (); HttpClient Client=httpclientbuilder.create (). setdefaultrequestconfig (config). build (); HttpGet Htget=NewHttpGet (Requrl); //Add HTTP Headers if(Headers! =NULL&& headers.size () > 0) { for(String key:headers.keySet ()) {Htget.addheader (key, Headers.get (key)); } } //reading DataHttpResponse r =Client.execute (Htget); Inch=NewBufferedReader (NewInputStreamReader (R.getentity (). GetContent (), charsets.utf_8)); String Line; while(line = In.readline ())! =NULL) {result+=Line ; } } Catch(Exception e) {System.out.println ("Send GET request exception!" " +e); E.printstacktrace (); } finally { Try { if(In! =NULL) { in=NULL; } } Catch(Exception E2) {e2.printstacktrace (); } } returnresult; }}
HttpClient Set header and timeout when sending request requests