- Java code
private String getWebData(String strurl) { try { URL url = new URL(strurl); // 打开连接,此处只是创建一个实例,并没有真正的连接 HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setConnectTimeout(30000); httpCon.setReadTimeout(30000); httpCon.setDoOutput(true);//打开写入属性 httpCon.setRequestMethod("POST");//设置提交方法 httpCon.connect();//建立连接 InputStream inputStream = httpCon.getInputStream(); InputStreamReader inputReader = new InputStreamReader(inputStream,"utf-8"); BufferedReader bufferReader = new BufferedReader(inputReader); StringBuffer sb = new StringBuffer(); String inputLine = null; while ((inputLine = bufferReader.readLine()) != null) { sb.append(inputLine+"\n"); } bufferReader.close(); inputReader.close(); inputStream.close(); httpCon.disconnect(); System.out.println(sb.toString().trim()); return sb.toString(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("======================================================="); return null; }
以上是源代码,异常信息如下:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:837)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:778)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:703)
at com.joye.util.UpdateAppData.getWebData(UpdateAppData.java:174)
at com.joye.util.UpdateAppData.getAppDetails(UpdateAppData.java:137)
at com.joye.util.TimerGetData.run(TimerGetData.java:11)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
求救:这个连接超时的异常,该如何解决呢?
httpCon.setConnectTimeout(30000);
我已经设置了超时重连的时间啊!
------解决方案--------------------------------------------------------
什么叫超时重连?你没有做过任何重连的动作啊
httpCon.setConnectTimeout(30000);
这个设置就是,设置如果连接在30秒后还没有连接上就返回timeout异常
------解决方案--------------------------------------------------------
setConnectTimeout();把这个设大一点差不多就OK了吧!