VBAでWinHttp.WinHttpRequestで画面引き継ぐには、Keep-Aliveが必要だった
Web上のログイン画面とか色々とexcelVBAでちょちょいと調べたりする事あるじゃないですか。
で、WEBAPIを叩いてたですが、
1番目のapiでcodeを取得して、そのcodeで
2番目のapiを叩くみたいな処理をexcelVBAで作ってたら、何故かエラー。
Dim url As String Const app_id = "AAA" Const secret = "BBB" url = "https://hoge.com/v1/oauth?app_id=" & app_id Dim xmlhttp As Object Dim xNode As Object Dim xNode2 As Object Dim retCd As String Dim xdoc As Object Dim code As String Dim AccessToken As String Set xmlhttp = CreateObject("WinHttp.WinHttpRequest.5.1") xmlhttp.Open "GET", url, False xmlhttp.send (Null) retCd = xmlhttp.Status '結果コード取得 If retCd <> 200 Then Debug.Print "error:" & retCd Exit Sub Else Debug.Print xmlhttp.getAllResponseHeaders() 'Debug.Print StrConv(xmlhttp.responsebody, vbUnicode) code = getValueFromXml(StrConv(xmlhttp.responsebody, vbUnicode), "Code") End If url = "https://hoge.com/v1/token" xmlhttp.Open "POST", url, False xmlhttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" Dim postData As Variant postData = "grant_type=oauth_code&app_id=" & app_id & "&secret=" & secret & "&code=" & code xmlhttp.send ("grant_type=oauth_code&app_id=" & app_id & "&secret=" & secret & "&code=" & code)
全くうまく行かない。
ブラウザでやるとうまくいきます。
最初cookieと思って、レスポンスヘッダーを調べてみたら何も入ってない!
なんだ!
と色々と悩んだ結果、Keep-Aliveを設定したら動いたというオチ。
xmlhttp.SetRequestHeader "Connection", "Keep-Alive"
こんな事あるんだ。
2時間返せ