[英]My app can't send a GET, OkHttp
我有一个奇怪的问题。
我在localhost:8080
有服务,并且一切配置都很好,我可以使用Android设备(真实的,不是模拟器)在浏览器中打开此服务。 我认为我的代码有问题。
但是在应用程序中,我得到了java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8080
这是我的代码:
private void sendGET() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("admin", "admin");
return response.request().newBuilder().header("Authorization", credential).build();
}
});
Request request = new Request.Builder()
.url("http://localhost:8080/users")
.build();
client.build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.w("http", e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.w("http", response.body().string());
}
});
}
这里有什么问题?
localhost
如何映射到实际IP地址可能存在问题。 尝试使用您的实际IP地址:
Request request = new Request.Builder()
.url("http://192.168.0.1:8080/users") // for example
.build();
以上假设IP地址为192.168.0.1
。
要查找您的IP地址,请在Windows上键入ipconfig
或在Linux上键入ifconfig
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.