LoginSignup
4
1

More than 3 years have passed since last update.

QiitaのAPIを呼ぶときに末尾にスラッシュをつけるとhttp://~にリダイレクトされるので気をつけましょう

Last updated at Posted at 2020-09-15

TL;DR

タイトル通り。curlの結果はこちら

iOS懐かしのエラー

昔よく見たエラーにふとした拍子に出くわししました:yum: 1

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.

これはメッセージの通り、HTTP通信をしようとしたときにiOSがブロックしてくる奴です。

QiitaのAPIを呼ぼうとしていた

URLSessionに渡しているurlは間違いなくhttpsのはず……:thinking:

let url = URL(string: "https://qiita.com/api/v2/items/?per_page=3")!
let task = urlSession.dataTask(with: url) { data, response, error in
    ...

エラーメッセージを確認してみる

- Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x6000007b4b40 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://qiita.com/api/v2/items, NSErrorFailingURLKey=http://qiita.com/api/v2/items, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

:astonished:?!:astonished:

NSErrorFailingURLKey=http://qiita.com/api/v2/items?per_page=3

なぜだかわかりませんが、URLスキームがhttpに変わっています???

そして、ローカルホストに繋いだりするときと同じように、App Transport Security Settings の Allow Arbitrary Loads を YES に設定すると問題なく結果が返ってきました。

犯人は……?

小一時間ハマったのち、ようやく犯人が見つかりました。2

let url = URL(string: "https://qiita.com/api/v2/items/?per_page=3")!

:rolling_eyes: よく見ると、URLの末尾にスラッシュがついている……? :rolling_eyes:

え?でも、このURLをcurlで叩いても普通にレスポンスが返ってきてたような?

もう一度curlで叩いてみた

$ curl -D - https://qiita.com/api/v2/items/ 
HTTP/2 301 
date: Tue, 15 Sep 2020 12:45:32 GMT
content-type: text/html
content-length: 178
location: http://qiita.com/api/v2/items
server: nginx

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>

:astonished:?!:astonished:

:innocent:なぜかhttpにリダイレクトされています:innocent:3

QiitaのAPIを使うときは、末尾のスラッシュに気をつけましょう

という結論でした:see_no_evil:

let url = URL(string: "https://qiita.com/api/v2/items?per_page=3")!

万が一同じ現象に遭遇した人がいれば、ここに辿り着けますように。


  1. リリース前の開発ではいまでもよく見るかもしれませんね。 

  2. 当初はmacOSのプロジェクトで試していたため、普段触ることのないサンドボックスの設定などを疑っていたため、どハマりしてしまいました。 

  3. そういえば調査の途中でcurl使ったときには、無意識に-Lオプションをつけていたような……:thinking: 

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1