Kotlin coroutines + Retrofit 2 で APIを叩くのに当たって、エミュレータとWebサーバーの設定をしなければならなかったのでメモ
1.ネットワーク・セキュリティの設定
1. ネットワーク・セキュリティの設定を記述した xml を作る
以下の xml を app/res/xml に作成します。ここでは network_security_config.xml とします。
普段Web開発をしている方ですと、接続先のホスト名をlocalhost 又は 127.0.0.1 としてしまいそうですが、これだと接続でしません。
というのも、ローカルPCには、10.0.2.2 というIPが割り当てられているようです。なのでdomainは10.0.2.2と指定する必要があります。
app/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">http://10.0.2.2</domain>
</domain-config>
</network-security-config>
2. network_security_config.xml を AndroidManifest.xml から読み込まれるようにする
applicationにandroid:networkSecurityConfig="@xml/network_security_config"を追加する
app/manifests/AndroidManifest.xml
<manifest>
<application
android:networkSecurityConfig="@xml/network_security_config"
>
</application>
</manifest>
2. Webサーバー(Flask)のポートを変更する
Flaskはデフォルトでhttp://127.0.0.1:5000 にサーバーが立つのですが、エミュレータからは80番でアクセスされるため、ポート番号を変更する必要があります。
app.run()となっているところを下記のように変更しましょう!
注意点
・ポートを80番に変更する際に、127.0.0.1から0.0.0.0に変更すること
・サーバーを起動する際に、管理者権限で起動すること
server.py
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=80)
3. 参考記事
https://qiita.com/notona/items/8faf62872a032b2d728d
http://blog.ceed.jp/?p=298