Httpclient Server Request

Source: Internet
Author: User
Import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. reader; import Java. io. unsupportedencodingexception; import java.net. httpurlconnection; import java.net. sockettimeoutexception; import java.net. URL; import java.net. urlencoder; import Java. util. arraylist; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import Java. util. map. entry; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. httpversion; import Org. apache. HTTP. client. clientprotocolexception; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. client. Params. httpclientparams; import Org. apache. HTTP. conn. clientconnectionmanager; import Org. apache. HTTP. conn. connecttimeoutexception; import Org. apache. HTTP. conn. params. connmanagerparams; import Org. apache. HTTP. conn. params. connperroutebean; import Org. apache. HTTP. conn. scheme. plainsocketfactory; import Org. apache. HTTP. conn. scheme. scheme; import Org. apache. HTTP. conn. scheme. schemeregistry; import Org. apache. HT TP. conn. SSL. sslsocketfactory; import Org. apache. HTTP. entity. stringentity; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. impl. conn. tsccm. threadsafeclientconnmanager; import Org. apache. HTTP. message. basicnamevaluepair; import Org. apache. HTTP. params. basichttpparams; import Org. apache. HTTP. params. httpconnectionparams; import Org. apache. HTTP. params. httpparams; import Org. apache. HT TP. Params. httpprotocolparams; import org. Apache. http. Protocol. HTTP;/*** optimizes httpclient to solve thread security, duplicate connection pool, and other performance problems. * **/Public class httputils {private final static Boolean DEBUG = false; public final static string charset = "UTF-8 "; /*** This defines the timeout time for establishing a connection with the server through the network. The httpclient package uses an asynchronous thread to create a socket connection with the server *, which is the timeout time for the socket connection (milliseconds) */public final static int default_socket_timeout = 2000; /** This defines the timeout time for data reading through the socket, that is, the waiting time (in milliseconds) required to obtain response data from the server */public final static int wait_getdata_time = 4000; /** configure the maximum number of connections per host */public final static int default_host_connections = 50;/** and the maximum number of connections in the connection pool */public final static int default_max_connections = 50; /** socket cache size */public final static int Default_socket_buffer_size = 8192;/** This defines the timeout time for retrieving connections from the connection pool managed by connectionmanager (MS) */public final static int get_connect_time = 1000; private Static httpclient = NULL; Private Static synchronized httpclient gethttpclient () {If (httpclient = NULL) {final httpparams = new basichttpparams (); connmanagerparams. setTimeout (httpparams, get_connect_time); httpconnectionparams. setconnecti Ontimeout (httpparams, default_socket_timeout); httpconnectionparams. setsotimeout (httpparams, wait_getdata_time); connmanagerparams. setmaxconnectionsperroute (httpparams, new connperroutebean (default_host_connections); connmanagerparams. setmaxtotalconnections (httpparams, default_max_connections);/** send some requests first (for example, send only request headers) for testing. If the server is willing to receive the requests, send the request body */httpprotocolparams. setuseexpectcontinue (httpparams, true );/ * ** When data transmission is required, the system first checks whether there are reusable connections in the connection pool. If yes, the connection is reused. * At the same time, in order to ensure that the "reused" connection is indeed valid, it will be checked for its validity before reuse */httpconnectionparams. setstalecheckingenabled (httpparams, false); httpprotocolparams. setversion (httpparams, httpversion. http_1_1); httpprotocolparams. setcontentcharset (httpparams, HTTP. utf_8); httpclientparams. setredirecting (httpparams, false); // set the proxy string useragent = "Mozilla/5.0 (windows; U; Windows NT 5.1; ZH-CN; RV: 1.9.2) gecko/20100115 Firefox/3.6 "; httppr Otocolparams. setuseragent (httpparams, useragent); // disable Nagle algorithmhttpconnectionparams. settcpnodelay (httpparams, true); httpconnectionparams. setsocketbuffersize (httpparams, default_socket_buffer_size); // configure HTTP and httpsschemeregistry schemeregistry = new schemeregistry (); schemeregistry. register (New Scheme ("HTTP", plainsocketfactory. getsocketfactory (), 80); schemeregistry. register (New sch EME ("HTTPS", sslsocketfactory. getsocketfactory (), 443); clientconnectionmanager manager = new threadsafeclientconnmanager (httpparams, schemeregistry); httpclient = new defaulthttpclient (Manager, httpparams);} return httpclient ;} public static inputstream dohttpclientpost (string URL, hashmap <string, string> Params) {If (Debug) {system. out. println ("dopost URL is" + URL);} httpclient = gethtt Pclient (); httppost httprequest = new httppost (URL); List <basicnamevaluepair> httpparams = new arraylist <basicnamevaluepair> (); iterator <entry <string, string> iter = Params. entryset (). iterator (); While (ITER. hasnext () {map. entry <string, string> entry = ITER. next (); string key = entry. getkey (); string val = entry. getvalue (); httpparams. add (New basicnamevaluepair (Key, Val);} inputstream = NUL L; string erromsg = NULL; try {httprequest. setentity (New urlencodedformentity (httpparams, HTTP. utf_8);} catch (effece) {} httpresponse = NULL; try {httpresponse = httpclient.exe cute (httprequest);} catch (clientprotocolexception e) {erromsg = E. getmessage (). tostring (); E. printstacktrace ();} catch (ioexception e) {erromsg = E. getmessage (). tostring (); E. printstacktrace ();} Int statuscode = httpresponse. getstatusline (). getstatuscode (); If (statuscode = 200) {try {inputstream = httpresponse. getentity (). getcontent ();} catch (illegalstateexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}} else {erromsg = "error response:" + httpresponse. getstatusline (). tostring ();} If (erromsg! = NULL) {system. out. println ("dopost error, error message is" + erromsg);} return inputstream;} public static inputstream dohttpsclientpost (string URL, string Params) {If (Debug) {system. out. println ("dopost URL is" + URL);} httpclient = gethttpclient (); httppost httprequest = new httppost (URL); inputstream = NULL; string erromsg = NULL; try {httpentity entity = new stringentity (PAR AMS, "UTF-8"); httprequest. setentity (entity);} catch (effece) {} httpresponse = NULL; try {httpresponse = httpclient.exe cute (httprequest);} catch (clientprotocolexception e) {erromsg = E. getmessage (). tostring (); E. printstacktrace ();} catch (ioexception e) {erromsg = E. getmessage (). tostring (); E. printstacktrace ();} int statuscode = httpresponse. getstatusline (). getstatu Scode (); If (statuscode = 200) {try {inputstream = httpresponse. getentity (). getcontent ();} catch (illegalstateexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}} else {erromsg = "error response:" + httpresponse. getstatusline (). tostring ();} If (erromsg! = NULL) {system. out. println ("dopost error, error message is" + erromsg);} return inputstream;} public static inputstream dohttpclientget (string URL, hashmap <string, string> Params) {httpclient = gethttpclient (); If (Debug) {system. out. println ("doget the URL before encode is" + URL);} If (Params! = NULL) {string paramstr = ""; try {iterator <entry <string, string> iter = Params. entryset (). iterator (); While (ITER. hasnext () {map. entry <string, string> entry = ITER. next (); string key = entry. getkey (); Key = urlencoder. encode (key, "UTF-8"); string val = entry. getvalue (); val = urlencoder. encode (Val, "UTF-8"); paramstr + = paramstr = "&" + key + "=" + val ;}} catch (unsupportedencodingexception E1) {e1.pr Intstacktrace ();} If (! Paramstr. Equals ("") {paramstr = paramstr. replacefirst ("&","? "); Url + = paramstr ;}} if (Debug) {system. out. println ("doget the URL after encode is" + URL);} httpget httprequest = NULL; try {httprequest = new httpget (URL);} catch (illegalargumentexception e) {system. out. println ("URI argument error"); return NULL;} inputstream = NULL; httpresponse = NULL; try {httpresponse = httpclient.exe cute (httprequest);} catch (illegalstateexception E) {e. Printstacktrace ();} catch (clientprotocolexception e) {e. printstacktrace ();} catch (sockettimeoutexception e) {e. printstacktrace ();} catch (connecttimeoutexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} catch (exception e) {e. printstacktrace ();} If (httpresponse = NULL) {system. out. println ("no response from server"); return NULL;} If (httpresponse. getstatusline (). gets Tatuscode () == 200) {httpentity = httpresponse. getentity (); try {inputstream = httpentity. getcontent ();} catch (illegalstateexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} else {system. out. println ("error response:" + httpresponse. getstatusline (). tostring ();} return inputstream;} // unoptimized Acoustic method public static string dohttpurlconnection (string myurl) throws ioexception {inputstream is = NULL; // only display the first 1000 characters of the retrieved // web page content.int Len = 1000; try {URL url = new URL (myurl); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setreadtimeout (10000/* milliseconds */); Conn. setconnecttimeout (15000/* milliseconds */); Conn. setrequest Method ("get"); Conn. setdoinput (true); // starts the queryconn. connect (); int response = Conn. getresponsecode (); If (Debug) {system. out. println ("the response is:" + response);} is = Conn. getinputstream (); // convert the inputstream into a stringstring contentasstring = readit (is, Len); Return contentasstring; // makes sure that the inputstream is closed after the app is // finished using it .} finally {If (Is! = NULL) {is. close () ;}}// reads an inputstream and converts it to a string. public static string readit (inputstream stream, int Len) throws ioexception, unsupportedencodingexception {If (Stream = NULL) return NULL; reader = new inputstreamreader (stream, UTF-8); char [] buffer = new char [Len]; reader. read (buffer); return new string (buffer );}}


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.