簡體   English   中英

從 android 模擬器連接本地主機失敗

[英]Failed to connect localhost from android emulator

我從 .net 創建了 rest api。 我有簡單的登錄和注冊 android 應用程序。 這是我綁定本地 ip 的代碼

public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance() {
        if (instance == null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://localhost:5000/")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        return instance;
    }
}

當我運行應用程序並測試我的登錄 function 它返回

無法連接到 localhost/127.0.0.1:5000

我該如何解決這個問題

模擬器顯示

模擬器設置

您需要創建一個 xml 並在該 xml 文件中寫入以下代碼

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">your sub domain</domain>
</domain-config>
</network-security-config>

文件的位置應為

** main/res/xml/network_security_config.xml**

並將此文件添加到應用程序標記的清單中,如下所述:

<application
......
android:networkSecurityConfig="@xml/network_security_config">

解釋:

由於 localhost 不是安全域,因此您必須在 API 28+ 的網絡配置中允許非安全域,默認情況下會阻止非 TLS 連接。

在我的例子中,在 localhost 上運行的服務器意味着 127.0.0.1:5000。 我已將此更改為我的本地 IP 地址,即 192.168.xx:5000 以運行服務器。 然后它起作用了。 希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM