HttpURLConnection, getResponseCode, and network timeout summary.

Source: Internet
Author: User

Yesterday, I made a connection timeout function. After checking the Internet, spark network timeout many of them implement a thread in the Activity to record the time. When the time is up, shut down the connection thread and remind me to time out. However, the younger brother is not talented and cannot read other people's code. The solution is to implement the network timeout function in the connection class HttpURLConnection. By the way, I understand the knowledge about the HttpURLConnect class. First, go to the code. This is a help class for network communication.how to fix nba live mobile network timeout

Public class HttpAssist {public static String doPost (JSONObject json) {System. out. println (json. toString (); try {URL postUrl = new URL (Config. url); HttpURLConnection connection = (HttpURLConnection) postUrl. openConnection (); connection. setDoOutput (true); connection. setDoInput (true); connection. setConnectTimeout (10000); // set the connection timeout to 10 s. setReadTimeout (10000); // read data timeout is also 10 s connection. setR EquestMethod ("POST"); connection. setUseCaches (false); connection. connect (); <span style = "white-space: pre"> </span> // you must set the connection Attribute before connection. OutputStreamWriter out = new OutputStreamWriter (connection. getOutputStream (); out. write (Config. getParameterName + "=" + json. toString (); out. flush (); out. close (); BufferedReader reader = new BufferedReader (new InputStreamReader (connection. getInputStream (), "UTF-8"); String line = ""; String res = ""; while (line = reader. readLine ())! = Null) {res + = line; System. out. println (line);} reader. close (); connection. disconnect (); return res;} catch (Exception e) {e. printStackTrace (); return "error ";}}}

network timeout 

Through this class, we can implement the reminder of network connection timeout. The principle is to use the exception throwing mechanism. The connection we set earlier. setConnectTimeout (10000); and connection. setConnectionTimeout (10000); I didn't use this timeout setting at the beginning. I thought that if the two timeout attributes were set, revelation online network connection timeout I would return something to tell us that the network has timed out. The result is that he does not return anything and directly throws an exception. And the connection is no longer connected, and the subsequent code will not be executed. In this case, we can capture exceptions to return things. The MalformedURLException exception is returned if it is an exception that is not reported. In addition, the exception of IOException is reported during openConnection. This is because there are not many codes. The attention we write is generally not error-free, so I directly put all the code in the try {} statement. Only catch one ion. (Lazy people are so lazy --!) In this way, as long as there is an exception capture, I will return a "error" string. In this way, the network error result can be obtained. We can do other operations. The above is the method to achieve network timeout. Then, I learned about the HttpURLConnection class through the query. During the query, someone said that connection. getResponseCode () is used to determine the result. Different return operations are implemented based on different codes. First of all, I think what he said makes sense. It should be able to achieve what I want. Second, when will this thing be judged? That is where this sentence is used. This is because I am not familiar with the web development because I use a browser to pass values. I will continue to check. The result is not displayed for half a day. If you cannot find it, print it out in the program. So it is printed everywhere in the program .... The result is that this sentence is useful only after you pass a value to the network. Later, I thought right. This is the returned status value after the communication is sent. Of course, timeout or other network error you must send data to the background before executing this statement. It's really fucking dead-headed... Specifically, in my code
out.flush();  

 sirius network timeout

The getResponseCode () method does not report an exception. If it was previously used, an exception or error will be reported directly, and the subsequent statements will not be executed. I don't know if you have any questions. I remember reading some articles about HttpURLConnection. There is a conclusion that, whether post or get, the http request is actually sent only in the getInputStream () function of HttpURLConnection. Let's leave this sentence right or wrong. So why can we use the getResponseCode () method after out. flush. And the value 200 is returned, that is, the communication is successful. This is a bit confusing. Please advise. For the time being, let's use the returned value to determine whether to write the getResponseCode () statement after getInputStream. Just in case. However, the connection timeout still fails. Because if the timeout occurs, the code segments will not be followed. So in the future, use the above method to write the timeout function. Then, I will attach some other summary about HttpURLConnection: a :) the connect () function of HttpURLConnection actually only establishes a tcp connection with the server and does not actually send http requests. Whether it is post or get, the http request is not officially sent until the getInputStream () function of HttpURLConnection. B: When using POST to send a URL request, the Setting Order of URL request parameters is the top priority. All configurations of the connection object (that pile of set functions) must be in connect () function execution is completed. The write operation on outputStream must be performed before the read operation on inputStream. These sequences are actually determined by the format of the http request. If the inputStream read operation is performed before the write operation of outputStream, the exception java.net. ProtocolException: Cannot write output after reading input... will be thrown ....... C: The http request is actually composed of two parts: one is the http header, and all configurations about this http request are defined in the http header, and the other is the body content. The connect () function generates http header information based on the configuration value of the HttpURLConnection object. Therefore, you must prepare all the configurations before calling the connect function. D: The http header is followed by the http Request body. The body content is written through the outputStream stream. In fact, outputStream is not a network stream, but a string stream at best, the content written into the file is not immediately sent to the network, but exists in the memory buffer. When the outputStream stream is closed, the http body is generated based on the input content. Now, all http request items are ready. When the getInputStream () function is called, the prepared http request is formally sent to the server, and an input stream is returned to read the server's response to this http request. Because the http request has been sent out (including the http header and body) during getInputStream, the connection object is set after the getInputStream () function (the http header information is modified) or writing outputStream (modifying the body) is meaningless. executing these operations will cause exceptions.


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.