簡體   English   中英

無法從Android模擬器訪問Rails-API-Server

[英]Cannot reach Rails-API-Server from Android Emulator

我有一個運行在localhost:3000上的Rails-api。 我有一個Android應用設置來驗證用戶身份(登錄)。 我正在使用Retrofit 這是設置:

`
    String BASE_URL = "http://192.168.0.104:3000";
    if(retrofit == null){
        retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    }
    return retrofit;
`

我可以從實際設備撥打電話。 完美的作品。

我想使用Android模擬器執行相同的操作。 而且,它不起作用。 我經歷了一些android文檔和其他Stack Overflow問題。 我發現您無法使用實際IP(例如192.168.0.104)訪問主機。 我必須使用10.0.2.2 然后我這樣做:

`
String BASE_URL = "http://10.0.2.2:3000";
`

盡管如此,它仍然無法正常工作。

這就是我打電話的方式。

`
Call<User> call = apiInterface.performUserLogin(mEmail, mPassword);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    ...
    ...
});
`

call.enqueue(new Callback()開始 ,執行似乎失敗了。回調根本沒有執行,而且我也不知道為什么。

剛剛在日志中找到了

`
08-08 18:46:12.659 13835-13835/com.example.gist.toasms E/Exception: java.net.UnknownServiceException: CLEARTEXT communication to 10.0.2.2 not permitted by network security policy

One of the solution was to add在清單中One of the solution was to add android:usesCleartextTraffic =“ true”`,但只能從minSdkVersion 23獲得。Mine是22

謝謝!

要直接回答您的問題,添加在比您的最低SDK級別更高的SDK級別引入的屬性沒有問題。 在其引入之前,它將被設備忽略。 您確實會在AndroidStudio中收到警告,但可以根據需要將其取消。 只需添加: tools:ignore="UnusedAttribute"

為了獲得更完整的答案,默認情況下,Android 9.0(SDK 28)開始禁用明文網絡通信。 請參閱已禁用Android 9.0(SDK 28)明文

您可以按照安全性偏好的順序選擇幾個選項:

  • 將所有網絡訪問更改為使用HTTPS。
  • 將網絡安全配置文件添加到您的項目中,以允許明文到不支持HTTPS的特定域。
  • 通過將android:usesCleartextTraffic="true"到清單中的應用程序,為應用程序啟用Cleartext支持。

要將網絡安全文件添加到項目中,您需要做兩件事。 您需要將文件規范添加到清單中:

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

其次,創建文件res / xml / network_security_config.xml並指定您的安全需求:

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

暫無
暫無

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

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