我是android開發的新手。我正在開發一個android應用程序,其中我向Web服務器發送請求并解析json對象。我經常java.net.SocketTimeoutException: Connection timed out在與服務器通信時遇到異常。有時它會完美地工作而不會出現任何問題。我知道這個問題已經問過很多次了。但是我仍然沒有得到令人滿意的解決方案。我在下面發布了我的logcat和應用程序服務器通信代碼。public JSONObject RequestWithHttpUrlConn(String _url, String param){ HttpURLConnection con = null; URL url; String response = ""; Scanner inStream = null; PrintWriter out = null; try { url = new URL(_url); con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); if(param != null){ con.setFixedLengthStreamingMode(param.getBytes().length); } con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); out = new PrintWriter(con.getOutputStream()); if(param != null){ out.print(param); } out.flush(); out.close(); inStream = new Scanner(con.getInputStream()); while(inStream.hasNextLine()){ response+=(inStream.nextLine()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(con != null){ con.disconnect(); }if(inStream != null){ inStream.close(); }if(out != null){ out.flush(); out.close(); } }}誰能幫我找出解決方案?提前致謝....
3 回答

收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
我在網上搜索了很多,并且在閱讀了許多有關連接超時異常的文檔后,我了解到的是,防止SocketTimeoutException超出了我們的限制...一種有效的處理方法是定義連接超時并稍后處理通過使用try catch塊來實現。...希望這將對以后遇到相同問題的任何人有所幫助。
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000); //set the timeout in milliseconds

開滿天機
TA貢獻1786條經驗 獲得超13個贊
如果要在localhost中測試服務器,則必須將Android設備連接到相同的本地網絡。然后,您的APP使用的服務器URL必須包含您的計算機IP地址,而不是“ localhost”掩碼。
添加回答
舉報
0/150
提交
取消