環境
macOS Mojave 10.14.6
xcode11.0
iOS13.0
swift5.0.1
目的
接続先がhttp2に対応していないため、iOSアプリからhttp1.1によるhttp接続を行いたい
現状問題
- http1.1による接続(httpでリクエスト) をすると以下のようなエラーがでる。
Alamofire.request("http://~~").responseJSON { response in
debugPrint(response)
}
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
- http2による接続(httpsでリクエスト) をすると、以下のようなエラーがでる。
Alamofire.request("https://~~").responseJSON { response in
debugPrint(response)
}
Task <FEBC04C5-B90B-49E6-949B-C1A4B758ED90>.<1> finished with error [100] Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error"
解決方法
二つ目の問題は接続先の問題。
例えば、curlでリクエストしても、エラーが出る。-> curlコマンドによる挙動確認
よってクライアント側からできるのは、一つ目の問題の解決。
つまり、アプリから特定のdomainへのhttp接続を許可してやればいい。
そこで、info.plistに以下を追記。
info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>!!接続先domainを記述!!</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
これだけ。
curlコマンドによる挙動確認
httpによる接続 -> ok!
$ curl -vvv http://mudomain
---
< HTTP/1.1 200 OK
< Server: nginx
---
httpsによる接続 -> failure...
$ curl -vvv https://mudomain
---
Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 200
< server: nginx
< date: Sat, 23 Nov 2019 02:59:26 GMT
< content-type: text/html; charset=utf-8
< content-length: 748
<
* HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)
* stopped the pause stream!
* Connection #0 to host mydomain left intact
curl: (92) HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)
---
httpかつhttp2による接続 -> ok!
$ curl -vvv --http2 http://mydomain
---
> GET /mydomain HTTP/1.1
> Host: mydomain
> User-Agent: curl/7.66.0
> Accept: */*
> Connection: Upgrade, HTTP2-Settings
> Upgrade: h2c
> HTTP2-Settings: AAMAAABkAARAAAAAAAIAAAAA
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx
< Date: Sat, 23 Nov 2019 03:05:55 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 748
< Connection: keep-alive
---
httpだとhttp2による接続をリクエストしてもhttp1.1で接続されるらしい。
httpsかつhttp1.1による接続 -> ok!
$ curl -vvv --http1.1 https://mydomain
---
> GET /mydomain HTTP/1.1
> Host: mydomain
> User-Agent: curl/7.66.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx
< Date: Sat, 23 Nov 2019 03:04:13 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 748
< Connection: keep-alive
<
---