java.net.SocketTimeoutException:未连接传输端点

时间:2013-09-06 01:54:03

标签: android sockets http udp timeout

我正在使用Samsung Galaxy S开发我的应用程序,我已升级到Android 4.2。应用程序在此设备上正常运行。

当我在运行Android 2.2的手机上测试时,会发生异常。

我一次又一次地检查,发现问题发生在应用程序发送UDP DatagramPacket之后。

当我评论指向发送UDP DatagramPacket的代码时,问题永远不会发生。

有谁能告诉我这是为什么?如何解决问题?

主要方法:

 public static String getDataFromServerInPostMethod(String url,
        String content) {
    HttpURLConnection httpurlconnection = null;

    String result = "";
    try {
        InputStream stream = null;
        // String host = android.net.Proxy.getDefaultHost();
        // if (host != null) {
        // int port = android.net.Proxy.getDefaultPort();
        // SocketAddress vAddress = new InetSocketAddress(host, port);
        // java.net.Proxy vProxy = new java.net.Proxy(
        // java.net.Proxy.Type.HTTP, vAddress);
        // httpurlconnection = (HttpURLConnection) new URL(url)
        // .openConnection(vProxy);
        // } else {
        // httpurlconnection = (HttpURLConnection) new URL(url)
        // .openConnection();
        // }
        httpurlconnection = (HttpURLConnection) new URL(url)
                .openConnection();
        httpurlconnection.setDoOutput(true);
        httpurlconnection.setRequestMethod("POST");
        // httpurlconnection.setRequestProperty("Connection", "Keep-Alive");
        httpurlconnection.setReadTimeout(TIMEOUT * 1000);
        httpurlconnection.setConnectTimeout(TIMEOUT * 1000);
        try {
            httpurlconnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpurlconnection.connect();
        MyLog.e(TAG, "getURL:" + httpurlconnection.getURL());
        httpurlconnection.getOutputStream().write(content.getBytes());
        httpurlconnection.getOutputStream().flush();
        httpurlconnection.getOutputStream().close();
        stream = httpurlconnection.getInputStream();
        result = SystemUtil.convertStreamToString(stream);
        if (httpurlconnection.getResponseCode() == 200) {
            MyLog.w(TAG,
                    "Responsed-->>getURL:" + httpurlconnection.getURL());
        } else {
            MyLog.e(TAG,
                    "not Responsed,ResponseCode:"
                            + httpurlconnection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpurlconnection != null) {
            httpurlconnection.disconnect();
        }
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

您是否在AndroidManifest.xml文件中拥有此权限?

<uses-permission android:name="android.permission.INTERNET" />