所以我试图从Node.js服务器读取一个Android应用程序。这是节点服务器的代码

exports.init = function (app) {
    app.get('/Ping', ping);
}

function ping(req, res, next) {
    res.end('Response');
}


-下一个编辑-

所以我将其更改为异步,这是我为此做的代码

protected String doInBackground(String... params) {
try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("http://localhost/ping"); //localhost in place of actual ip
    HttpResponse response = httpClient.execute(httpGet, localContext);
    String result = "";

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

    String line = null;
    while ((line = reader.readLine()) != null) {
        result += line + "\n";
        pageResult = result;
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

// TODO Auto-generated method stub
return pageResult;
}


但是,当我在这里运行它时,它返回的是html(请注意,稍后我将解析出html)

<HTML>
    <HEAD>
        <TITLE>401 Unauthorized</TITLE>
    </HEAD>
    <BODY BGCOLOR="#CC9999">
        <H4>401 Unauthorized</H4>
            Authorization required. please note that the default username is "root" in all newer releases
    </BODY>
</HTML>

最佳答案

尝试更换

URLConnection urlConnection = url.openConnection();




HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();


并添加

urlConnection.setRequestMethod("GET");


另外,如果抛出异常,则应该在finally子句中关闭输入流。

编辑:

首先,使用堆栈跟踪而不是答案编辑问题:)

其次,好的,您将收到NetworkOnMainThreadException。这意味着您必须运行AsyncTask并在AsyncTask的doInBackground方法中执行该操作。

09-11 19:22
查看更多