在Android中连接到localhost

时间:2016-10-26 07:50:41

标签: android http url localhost httprequest

我正在开发一个应用程序,并设计了一些前端和后端,只是必不可少的。现在,我想连接双方。首先,我需要知道如何连接到Android中的localhost。

我在互联网上尝试了一些教程,例如:

URL url = new URL("http://127.0.0.1");
HttpURLConnection urlConnection = (HttpURLConnection)
 url.openConnection();
try {
 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
} finally {
 urlConnection.disconnect();
}

我尝试了几种方法,但都失败了。有些人没有做任何事情,其他人则停止了应用程序显示一些Zygote错误。

我的问题很清楚。如何在Android中连接到localhost?我想要一个样式makeConnectionLocalHost()的函数,它返回连接是否成功。知道为什么没有用吗?

2 个答案:

答案 0 :(得分:1)

尝试使用“localhost”而不是本地IP。要检索它,请打开CMD并键入ipconfig。在那里你会找到你的本地IP。 127.0.0.1将创建一个回到您自己设备的循环。

答案 1 :(得分:0)

您可以使用InetAddress.getLocalHost()获取localhost地址。更多细节here。对于HttpURLConnection,您应该在此地址上安装Web服务器。