The Http request waits for a long time for no result to return a solution. The request Solution
Http request waits for a long time for no result to return Solution
Today, I encountered a strange problem. This program is mainly used to call interfaces to collect data. However, a bad thing is that there are many processes started on the server, which cannot be ended, there is no way to kill all the processes.
After analyzing the program and writing a test, the local running still waits for a long time, cannot run, and does not throw an exception. Finally, the problem is that the request is sent and is waiting for the response from the other server, because the keep-alive connection is used, the timeout method is not used here, so that the program will wait for a long time.
After testing, it is found that too many processes are enabled because no timeout is set. Readers are expected to pay attention to this part. Otherwise, this problem may easily occur. The final problem should be caused by an exception of the interface provider.
Public static String sendPost (String url, String param) {PrintWriter out = null; BufferedReader in = null; String result = ""; try {URL realUrl = new URL (url ); // enable the URL Connection URLConnection conn = realUrl. openConnection (); // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); conn. setConnectTimeout (4000); conn. setReadTimeout (4000); // The following two rows of conn must be set to send a POST request. setDoOutput (true); conn. setDoInput (true); // get the output stream of the URLConnection object out = new PrintWriter (conn. getOutputStream (); // sends the request parameter out. print (param); // flush the Buffer out of the output stream. flush (); // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line; w Hile (line = in. readLine ())! = Null) {result + = line;} catch (Exception e) {System. out. println ("an Exception occurred when sending the POST request! "); // E. printStackTrace () ;}// use finally blocks to close the output stream and input stream finally {try {if (out! = Null) {out. close () ;}if (in! = Null) {in. close () ;}catch (IOException ex) {// ex. printStackTrace () ;}} return result ;}
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!