Android java.net.SocketTimeoutException:连接超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20046707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:40:08  来源:igfitidea点击:

Android java.net.SocketTimeoutException: Connection timed out

javaandroidsocketsexceptiontimeout

提问by user2424947

Recently I have encounter the following error in my program:

最近我在我的程序中遇到了以下错误:

11-18 12:30:30.259: W/System.err(21368): java.net.SocketTimeoutException: Connection timed out
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
11-18 12:30:30.259: W/System.err(21368):    at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
11-18 12:30:30.259: W/System.err(21368):    at java.net.Socket.connect(Socket.java:1002)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:75)
11-18 12:30:30.259: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
11-18 12:30:30.269: W/System.err(21368):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)
11-18 12:30:30.269: W/System.err(21368):    at com.example.simplevider.SimpleVideo.run(SimpleVideo.java:122)
11-18 12:30:30.279: W/System.err(21368):    at java.lang.Thread.run(Thread.java:1019)

The function that created this error is as follows :

创建此错误的函数如下:

    private void sendStuff() {
    Log.e("sendStuff", "======================================");
    new Thread(new Runnable() {

        @Override
        public void run() {
            final int BUFFER_SIZE = 4096;
            try {
                File uploadFile = new File(existingFileName);
                System.out.println("File to upload: " + existingFileName);
                URL url = new URL(URL);

                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setUseCaches(false);
                httpConn.setDoOutput(true);
                httpConn.setRequestMethod("POST");
                httpConn.setReadTimeout(60*1000);
                httpConn.setConnectTimeout(60 * 1000);
                // sets file name as a HTTP header
                httpConn.setRequestProperty("fileName", uploadFile.getName());
                httpConn.setRequestProperty("extra-id", uploadFile.getAbsoluteFile().toString());
                httpConn.setRequestProperty("extra-id2", uploadFile.getParent());
                httpConn.setRequestProperty("extra-id3", uploadFile.length() + "");



                OutputStream outputStream = httpConn.getOutputStream(); //<< this is the source of the error


                FileInputStream inputStream = new FileInputStream(uploadFile);

                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = -1;

                System.out.println("Start writing data...");

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                System.out.println("Data was written.");
                outputStream.close();
                inputStream.close();

                // always check HTTP response code from server
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // reads server's response
                    BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                    String response = reader.readLine();
                    System.out.println("Server's response: " + response);
                } else {
                    System.out.println("Server returned non-OK code: " + responseCode);
                }

            } catch (Exception e) {
                e.printStackTrace();
                sendStuff();
            }

        }
    }).start();

}

This function is perfectly working in normal JAVA but when copied to Android it casts java.net.SocketTimeoutException: Connection timed outand I don't know why.

此功能在普通 JAVA 中完美运行,但当复制到 Android 时,它会强制转换java.net.SocketTimeoutException: Connection timed out,我不知道为什么。

采纳答案by Navin Kumar

There are two possibilities,

有两种可能,

1)have you checked and tested your connection.

1)您是否检查并测试了您的连接。

2)better don't set any connection timeout,if you are setting chose maximum time,,bcos it throws an error,if server didn't response within given time..

2)最好不要设置任何连接超时,如果你设置选择最大时间,bcos它抛出一个错误,如果服务器在给定时间内没有响应..

回答by Chitransh Mathur

You can use these code snippet for exception haldling:

您可以使用这些代码片段进行异常处理:

HttpURLConnection urlConnection = (HttpURLConnection) callUrl.openConnection();
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000);

回答by Aakib Jabbar

this type of exception can also occur if firewall blocks the http or https service and to unblock that goto

如果防火墙阻止 http 或 https 服务并取消阻止该 goto,也会发生这种类型的异常

firewall->advanced settings -> and check the http or https options and saveenter image description here

防火墙-> 高级设置 -> 并检查 http 或 https 选项并保存在此处输入图像描述