Java 爪哇元';t读取Node.js服务器
因此,我试图从Node.js服务器读取一个Android应用程序。以下是节点服务器的代码Java 爪哇元';t读取Node.js服务器,java,android,node.js,Java,Android,Node.js,因此,我试图从Node.js服务器读取一个Android应用程序。以下是节点服务器的代码 exports.init = function (app) { app.get('/Ping', ping); } function ping(req, res, next) { res.end('Response'); } -下一次编辑- 所以我把它改成了Async,下面是我为此编写的代码 protected String doInBackground(String... params
exports.init = function (app) {
app.get('/Ping', ping);
}
function ping(req, res, next) {
res.end('Response');
}
-下一次编辑-
所以我把它改成了Async,下面是我为此编写的代码
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)
401未经授权
401未经授权
需要授权。请注意,在所有较新版本中,默认用户名为“root”
尝试更换
URLConnection urlConnection = url.openConnection();
与
并加上
urlConnection.setRequestMethod("GET");
此外,您应该在finally子句中关闭输入流,以防引发异常
编辑:
首先,用堆栈跟踪编辑问题,而不是答案:)
其次,好的,您将获得一个NetworkOnMainThreadException。这意味着您必须运行,并在AsyncTask的doInBackground方法中执行这些操作。仍然存在问题。我照你说的做了,但是现在我得到了错误“android.os.NetworkOnMainThreadException”@Cciamlazy同一个错误?也许请求方法应该是POST?考虑到URL名为loginStill,我也会遇到同样的错误。它必须使用“http://”协议,因为当我取下它时,它不会使应用程序崩溃。当它确实有http时,会使应用程序崩溃。谢谢。我将尝试切换到AsyncTask,但现在我得到了一些关于所需授权的信息。检查我的编辑。
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");