【问题标题】:Android - Unnable to connect to node.js server with HttpURLConnection (Connection closed by peer)Android - 无法使用 HttpURLConnection 连接到 node.js 服务器(连接被对等方关闭)
【发布时间】:2015-12-24 20:37:17
【问题描述】:

我有一个简单的 node.js 服务器在 localhost:8080 运行,它提供一个简单的 api (json)。在浏览器上一切正常。我还制作了一个 android 应用程序,该应用程序应该连接并从 localhost:8080 获取 json 文件,但在连接 javax.net.ssl.SSLHandshakeException: Connection closed by peer 时简单地拒绝错误。它适用于其他网站,但不适用于我自己的 node.js 服务器。

我正在使用 AsyncTask 在后台检索请求,如下所示:

@Override
protected String doInBackground(String... params) {
    String result = "";

    HttpURLConnection connection = null;
    int statusCode = 0;

    try {
        URL url = new URL(params[0]);

        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("GET");

        statusCode = connection.getResponseCode();
        System.out.println("Async call code: " + connection.getResponseCode());

        if (statusCode ==  200) {
            System.out.println("Server responded with code: " + statusCode);

            InputStream inputStream = new BufferedInputStream(connection.getInputStream());

            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));

            String line = "";
            String res = "";

            while((line = bufferedReader.readLine()) != null){
                res += line;
            }

            /* Close Stream */
            if(null!=inputStream){
                inputStream.close();
            }

            parseResult(res);

        }
        else{
            System.out.println("error");
        }

    } catch (Exception e){
        System.out.println(e);
    }
    finally {
        connection.disconnect();
        System.out.println("disconnected");
    }

    return result;
}

【问题讨论】:

  • params[0] 是什么?我注意到您收到的异常表明您的代码正在尝试建立 HTTPS 连接,localhost:8080 HTTPS 还是 HTTP 也是如此?端口号强烈表明它是 HTTP,但如果它是 HTTPS(在这种情况下,我会将其移至 8443 以明确它是 HTTPS),它是否具有有效的证书?如果没有,您是否已安排您的代码接受自签名证书?
  • 您好,感谢您的帮助,您修复了我的帮助。 param[0] 是 localhost:8443,这是错误的,它应该是 localhost:8443。谢谢它现在可以工作了!
  • 对不起,但我不相信您的 android 应用程序可以使用 localhost 作为主机名来连接到您电脑上的服务器。不可能。

标签: android json node.js api server


【解决方案1】:

通过将 url 从 https://localhost:8443 更改为 http://localhost:8443 使其工作。这个 url 作为 param[0] 传递给上面的代码。现在一切正常!

【讨论】:

  • 大概你的意思是从:8443:8080?很高兴你成功了。
  • 适用于 8080 和 8443
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多