7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

POSTメソッド投げて、画像を取得するのは簡単だった

Posted at

Javaよりも簡単にできるね!!

でも、VBAって時点っでもうやる気がでない・・・VBAがマストなんだけど・・・

post.bas
'指定したURLからファイルをダウンロードする.
'srctUrl : ダウンロード先のURL
'distFilename : ダウンロード先のファイルパス
'postBody : 中身
'返り値 : 成功すればtrue
Function requestHttpPost(srcUrl As String, distFilepath As String, postBody As String) As Boolean
    Dim i As Long, bLength As Long 'ループカウンター,バイト長
    Dim fileNum As Integer '保存先ファイルのファイル番号
    Dim responseBody As String 'レスポンスの中身
    Dim temByte() As Byte  '一次バイト保存先
    Dim winHttp As Object  '通信用のオブジェクト
    
    
    Set winHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
    
    winHttp.Open "POST", srcUrl, False
    winHttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    winHttp.Send postBody
    
    'HTTP Status Code が200 -399の場合のみ処理を行う
    If winHttp.Status > 199 And winHttp.Status < 400 Then
        bLength = LenB(winHttp.responseBody)
        fileNum = FreeFile()
        Open distFilepath For Binary Access Write As #fileNum
        temByte() = winHttp.responseBody
        Put #fileNum, , temByte()
        Close #fileNum
        requestHttpPost = True
    Else
        requestHttpPost = False
    End If
    Exit Function

という訳で、画像に保存可能。

チョットわからないのが

        temByte() = winHttp.responseBody
        Put #fileNum, , temByte()

なにこれ?なんで一旦バイト配列に落としてるの?
winHttp.ResponseBody()ではなぜ駄目なんだ?

7
8
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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?