HTTP Timeout settings

Source: Internet
Author: User

The timeout can be set in the HTTP protocol (connection timeout, response timeout), as follows:

1, the Java API way:

Previous versions of JDK 1.5, you can only control network timeouts by setting two system properties:

String szurl = "http://www.ee2ee.com/"; URL url = new URL (szurl); HttpURLConnection Urlcon = (httpurlconnection) url.openconnection ();//httpurlconnection is based on the HTTP protocol, and its underlying is implemented via socket communication. If you do not set a time-out (timeout), in the case of a network exception, it may cause the program to zombie without continuing to execute. The corresponding timeout can be set by the following two statements: System.setproperty ("Sun.net.client.defaultConnectTimeout", string of timeout milliseconds); System.setproperty ("Sun.net.client.defaultReadTimeout", time-out number of milliseconds string);// Sun.net.client.defaultConnectTimeout: Timeout in milliseconds for connecting the host//sun.net.client.defaultreadtimeout: Time-out (in milliseconds) to read data from the host
In 1.5, you can also use the following two methods of HttpURLConnection's parent class URLConnection:
Setconnecttimeout: Setting the connection host timeout (in milliseconds)
Setreadtimeout: Setting read data timeout from host (in milliseconds)
HttpURLConnection Urlcon = (httpurlconnection) url.openconnection (); Urlcon.setconnecttimeout (30000); Urlcon.setreadtimeout (30000);
Note that, in the JDK1.4.2 environment, I found that in the case of setting up Defaultreadtimeout, if a network timeout occurs, HttpURLConnection will automatically resubmit the request, a request call, Request Server two times problem (trouble). I think this is a bug in JDK1.4.2. In JDK1.5.0, this issue has been resolved and there is no automatic re-occurrence. Out "," 30000″);

2, HttpClient:

HttpClient Tool class, each version of the different:
3.X is like this.
HttpClient httpclient=new defaulthttpclient ();
4.3 that's it.
Closeablehttpclient httpClient = Httpclients.createdefault ();

httpclient has three timeout settings:
1) 3. The timeout method for x is
HttpClient client = new HttpClient ();
Client.setconnectiontimeout (30000);  
Client.settimeout (30000);

HttpClient httpclient= New HttpClient ();  
Httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (5000);
2) 4. The x version of the timeout setting (4.3 is obsolete)
HttpClient httpclient=new defaulthttpclient ();
Httpclient.getparams (). Setparameter (coreconnectionpnames.connection_timeout,2000);//Connection Time
Httpclient.getparams (). Setparameter (coreconnectionpnames.so_timeout,2000);//Data transfer time
3) 4.3 version timeout setting
Closeablehttpclient httpClient = Httpclients.createdefault ();
HttpGet httpget=new httpget ("http://www.baidu.com");//http Get request (post identical)
Requestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (. setconnecttimeout). Build ();//Set request and transmit timeout time
Httpget.setconfig (Requestconfig);
Httpclient.execute (HttpGet);//Execute request


3. When using curl, there are two timeouts: one is the connection timeout time and the other is the maximum allowable time for data transfer.
The connection time-out is specified with the--connect-timeout parameter, and the maximum allowable time for data transfer is specified with the-m parameter.
For example:
Curl--connect-timeout 10-m "Http://XXXXXXX"
If the connection times out, the error message is as follows:
Curl: (+) Connect () timed out!
When the maximum allowable time for data transfer expires, the error message is as follows:
Curl: (operation) timed out after 0 bytes received milliseconds


4. Ajax:

1) in older versions of XMLHttpRequest, there is no timeout attribute, so if you use JavaScript native old Ajax requests, you can only do this by manually setting up settimeout and Cleartimeout ( These two methods are methods of the Window object)

function Createxmlhttprequest () {var request = false; if (window.          XMLHttpRequest) {request = new XMLHttpRequest ();          if (request.overridemimetype) {request.overridemimetype (' text/xml '); }} else if (window. ActiveXObject) {var versions = [' Microsoft.XMLHTTP ', ' MSXML. XMLHTTP ', ' microsoft.xmlhttp ', ' msxml2.xmlhttp.7.0 ', ' msxml2.xmlhttp.6.0 ', ' MSXML2.XMLHT tp.5.0 ', ' msxml2.xmlhttp.4.0 ', ' MSXML2. xmlhttp.3.0 ', ' MSXML2.          XMLHTTP ']; for (var i = 0; i < versions.length; i++) {try {request = new ActiveXObject (versions[i                  ]);                  if (request) {return request;  }} catch (e) {}}} return request;      } function Ajax (XMLHTTP, _method, _url, _param, _callback) {if (typeof xmlhttp = = ' undefined ') return; Xmlhttp.onreadystatechange= function () {if (xmlhttp.readystate = = 4 && Xmlhttp.status = =) {_callback (XMLHTTP);      }      };      Xmlhttp.open (_method, _url, true); if (_method = = "POST") {Xmlhttp.setrequestheader ("Content-type", "Application/x-www-form-urlenc          Oded ");          Xmlhttp.setrequestheader ("Content-length", _param.length);      Xmlhttp.send (_param);      } else {xmlhttp.send (null);  }}//use example var xmlhttp = Createxmlhttprequest (); var T1;      Used for timeout processing function Adduserok (request) {//alert (Request.responsetext);  if (T1) cleartimeout (t1);      } function Connecttofail () {if (XMLHTTP) xmlhttp.abort ();  Alert (' Time Out '); } if (XMLHTTP) {Ajax (XMLHTTP, "POST", "http://10.1.2.187/adduser.cgi", "Act=do&user=abc", Addusero      k);  T1 = SetTimeout (Connecttofail, 30000);  } else {alert ("Init XMLHttpRequest fail");   }
2) The above-mentioned manual processing of Ajax for the initial stage, if using the jquery framework, you can set the Timeout timeout property in jquery:

$.ajax ({url: ',///  request URL timeout:1000,//time-out setting, unit millisecond type: ' Get ',  //Request method, get or Post data: {},  //request parameter, J  Son format dataType: ' JSON ',//returns the data format success:function (data) {//Request successful callback function alert ("Success");       }, Complete:function (xmlhttprequest,status) {//The final execution of the parameter if (status== ' timeout ') {//timeout, status and Success,error equivalent when the request is completed     Ajaxtimeouttest.abort ();      alert ("timeout"); }  }});
3) XMLHttpRequest Level2 new version, the timeout attribute is added, and there is a timeout event:

Xhr.timeout = 3000;xhr.ontimeout = function (event) {alert (' Request timed out! ');}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

HTTP Timeout settings

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.