Android - 无法通过HttpURLConnection连接到node.js服务器(连接由对等关闭)

时间:2015-12-24 20:37:17

标签: android json node.js api server

我有一个简单的 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;
}

1 个答案:

答案 0 :(得分:0)

通过将网址从https://localhost:8443更改为http://localhost:8443来实现目标。这个url作为param [0]传递给上面的代码。现在everythig工作正常!