HttpClient Set header and timeout when sending request requests

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.