【发布时间】: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:8080HTTPS 还是 HTTP 也是如此?端口号强烈表明它是 HTTP,但如果它是 HTTPS(在这种情况下,我会将其移至 8443 以明确它是 HTTPS),它是否具有有效的证书?如果没有,您是否已安排您的代码接受自签名证书? -
您好,感谢您的帮助,您修复了我的帮助。 param[0] 是 localhost:8443,这是错误的,它应该是 localhost:8443。谢谢它现在可以工作了!
-
对不起,但我不相信您的 android 应用程序可以使用 localhost 作为主机名来连接到您电脑上的服务器。不可能。
标签: android json node.js api server