shinonome-inc / qiita_client_yo

【模擬開発案件】Qiitaクライアントアプリ(PlayGroundモバイルコース最終課題)
3 stars 0 forks source link

【エラー】http.postでresponseが返ってこない #23

Closed KobayashiYoh closed 2 years ago

KobayashiYoh commented 2 years ago

POST /api/v2/access_tokensを利用してアクセストークンを発行しようとしたところ、responseすら返ってこないということがあったのでメモ。

該当箇所のコード

    var response = await http.post(
      Uri.parse(url),
      headers: {'content-type': 'application/json'},
      body: {
        'client_id': QiitaAuthKey.clientId,
        'client_secret': QiitaAuthKey.clientSecret,
        'code': redirectUrlCode,
      },
    );


エラー文

bad state: cannot set the body fields of a request with content-type "application/json".

原因

APIドキュメントにContent-Type: application/json という指定があるにもかかわらず、それに従っていなかったのが原因みたいです。 ちなみに、Content-Typeが大文字か小文字かはあまり重要ではないみたいです。

解決策

bodyをjson形式にdecodeする。

      body: json.encode({
        'client_id': QiitaAuthKey.clientId,
        'client_secret': QiitaAuthKey.clientSecret,
        'code': redirectUrlCode,
      }),


参考

https://stackoverflow.com/questions/54849725/bad-state-cannot-set-the-body-fields-of-a-request-with-content-type-applicatio