【发布时间】:2015-06-26 09:42:58
【问题描述】:
我正在尝试在 android 中使用 REST 服务,但出现以下错误:
org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8080 refused
我已经介绍了权限:uses-permission android:name="android.permission.INTERNET"
我在模拟器中运行代码并且它可以工作,但是当我尝试在我的智能手机中运行时它失败了。
PD:当我在模拟器中运行时,我使用http://10.0.2.2:8080。
public boolean checkConnection(){
String res = "";
boolean serverUp = false;
try {
HttpClient client = new DefaultHttpClient();
//HttpGet request = new HttpGet("http://10.0.2.2:8080/prueba_conexion");
HttpGet request = new HttpGet("http://localhost:8080/prueba_conexion");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String linea = "";
while ((linea = rd.readLine()) != null) {
res += linea;
}
serverUp = Boolean.parseBoolean(res);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return serverUp;
}
【问题讨论】:
-
在这里发布您的代码...
-
Localhost 表示您正在使用的服务在您呼叫的同一设备(您的手机)上运行。如果这不正确,则您使用了错误的网络/IP 地址来访问 REST 服务。
-
将手机连接到同一个wifi网络,然后使用您的本地IP而不是localhost。
-
我需要连接 3G/4G 连接。
标签: android