无法连接到 localhost/127.0.0.1 android

问题描述 投票:0回答:7

我是android开发新手,并尝试通过retrofit库调用android中的本地.NET Web api服务。在 IIS 上启动我的 Web api 后,我收到此错误无法连接到 localhost/127.0.0.1 android。

当我按照建议做同样的事情时http://themakeinfo.com/2015/04/retrofit-android-tutorial/,它工作正常,但我的本地主机服务没有从android调用

我的服务网址是, http://localhost:52511/api/Values/getAllStudents/5

它也在浏览器中为我提供了 XML 格式的输出。

我也尝试过调用它,

public interface gitapi {
    @GET("/api/Values/GetProduct/{id}")      //here is the other url part.best way is to start using /
    public void getFeed(@Path("id") int id, Callback<gitmodel> response);
}

public class gitmodel {
    public int studentId;
    public String studentName;
    public String studentAddress;
}


String API = "http://10.0.2.2:52511";
public void CallService(View view){

        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API).build();
        gitapi git = restAdapter.create(gitapi.class);

        int id = 5;
        git.getFeed(id, new Callback<gitmodel>() {
            @Override
            public void success(gitmodel gitmodel, Response response) {
                Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getApplicationContext(), "Errors", Toast.LENGTH_LONG).show();
            }
        });
}

但运气不佳。

请告诉我需要在哪里进行更改才能使其正常工作。 ?

我在浏览器中得到的响应是,

<ArrayOfstudents xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/APICall.Controllers">
<students>
<studentAddress>valsad</studentAddress>
<studentId>1</studentId>
<studentName>Keval</studentName>
</students>
<students>
<studentAddress>Hyderabad</studentAddress>
<studentId>2</studentId>
<studentName>Honey</studentName>
</students>
</ArrayOfstudents>
android retrofit androidhttpclient
7个回答
24
投票

不要使用

127.0.0.1:<PORT>
,而是使用您的本地 IP


6
投票

您的情况与改造库无关。

与您的网络设置有关, 您的手机和IIS服务器必须在同一个局域网。

您可以按照以下方式关注。

  1. 在 IIS 服务器上启动 AP;
  2. 将 AP 与手机连接。

有时您需要关闭 IIS 服务器上的安全防火墙。


5
投票

我遇到了和你一样的问题(无法连接到localhost/127.0.0.1)。 首先我建议你阅读以下内容: android开发者指南(图片中的主要部分↓)

我拥有所有这些,即 A、B 和 C。作为 C(模拟器),我使用了 Genymotion。 我通过更改网络配置解决了我的问题。

重要提示:我在 baseURL 中的地址是:“localhost:8099/

让我们看看: 您应该点击 SettingsNetwork → 检查 Use HTTP Proxy → 输入您的 IP 地址和端口(在我的情况下是 8099)→ 关闭。更多详情请看图↓


0
投票

我有同样的问题,我通过更改IP地址而不是'localhost'来解决它:

  1. 打开cmd(如果您使用的是Windows):输入“ipconfig”并查看您计算机的IP。(确保您的计算机和Android设备连接到同一网络)。
  2. 删除网址中的“localhost”并使用 ip(步骤 1 中您计算机的 IP)。
  3. 再次运行项目并检查

0
投票

如果您使用 localhost,则需要更改机器 IP 的 URL 基数(在 Windows 中使用 cmd 中的 ipconfig 命令,并复制 IPV4 地址),并将其添加到 android 清单中: android:usesCleartextTraffic="true"


-3
投票

实际上,当在同一 Android 设备 (Android 9) 上使用 2 个应用程序时,这会有所帮助

android:usesCleartextTraffic="true"

-8
投票

您可以在

androidmanifest.xml

尝试一下
android:usesCleartextTraffic="true"
© www.soinside.com 2019 - 2024. All rights reserved.