Jump to content
Sign in to follow this  
big_daddy

Using WinHTTP to POST and Receive File

Recommended Posts

big_daddy

I was working on a solution for adamchapman on his topic here. I was able to make the option change quite easily, but downloading the file is a different story.

AutoIt Code to change select option

#include <IE.au3>

$sSymbol = "AA"
$sURL = "http://www.nasdaq.com/symbol/" & $sSymbol & "/historical"
$sFormId = "getFile"
$sSelectId = "ddlTimeFrame"
$sOptionValue = "5d"
$sInputId = "quotes_content_left_submitString"
$sLinkText = "Download this file in Excel Format"
$bDownload = False

_IEErrorHandlerRegister()
$oIE = _IECreate($sURL)
$oSelect = _IEGetObjById($oIE, $sSelectId)
_IEFormElementOptionSelect($oSelect, $sOptionValue)
If $bDownload Then _IELinkClickByText($oIE, $sLinkText)

I reviewed the function tied to the change event. This same function is called when you click the download link. The only difference is the argument is false and true respectively. I removed the code that is executed when false as it is not relevant for the issue. It basically builds a string with the selected option value + true + symbol (Example: 5d|true|AA), then sets the value of the input that has an id ending in submitString and submits the form.

function getQuotes(download) 
        {
            if(!download)
                showLoadingSpinner();
            
            var data = $("[id$='ddlTimeFrame']").val();
            var submitString = data + '|' + download + "|" + quoteBoxSelectedSymbol;
            
            if (!download) {
                <!-- Removed -->
            }
            else {
                $("[id$='submitString']").val(submitString);
                $("#getFile").submit();
            }
            
        }

-


Now we move on to the form that is submitted by the getQuotes function. The input with id "quotes_content_left_submitString" is the input that will have the value set from the previous function. 

<form id="getFile" method="post" action="http://www.nasdaq.com/symbol/aa/historical" lpsubdone="1">
    <div class="aspNetHidden">
        <input id="__VIEWSTATE" name="__VIEWSTATE" value="TRIMMED" type="hidden">
    </div>

    <div class="aspNetHidden">
        <input id="__VIEWSTATEENCRYPTED" name="__VIEWSTATEENCRYPTED" value="" type="hidden">
        <input id="__EVENTVALIDATION" name="__EVENTVALIDATION" value="FslL5mK8EfHMdRmVPirjPRHx0rzoR4ZblfHZcyVf/H6sJ58PbPdR2nXwJige52KEPcse4Wp37klD+PDrLXkhysNoAbltd+CEe5ntj67kFmk=" type="hidden">
    </div>
    <input id="quotes_content_left_submitString" name="ctl00$quotes_content_left$submitString" value="" type="hidden">
</form>

-


I believe this can be easily solved using WinHTTP, however I don't have a good understanding of that library currently. I did use Fiddler to capture the request and response that are generated when downloading the file.

Request

POST /symbol/aa/historical HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
X-SFS-Content-Type: text/html; charset=utf-8
X-SFS-Top: http://www.nasdaq.com/symbol/aa/historical
Referer: http://www.nasdaq.com/symbol/aa/historical
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: www.nasdaq.com
Content-Length: 5687
Connection: Keep-Alive
Pragma: no-cache
Cookie: c_enabled$=true; clientPrefs=||||black; asi_segs=C10001|C10003|C10023|C0; s_pers=%20bc%3D1%7C1372648582375%3B%20s_nr%3D1372562217412-New%7C1380338217412%3B; userSymbolList=AA+; userCookiePref=true; s_sess=%20s_cc%3Dtrue%3B%20s_sq%3Dnasdaqprod%253D%252526pid%25253D%25252528AA%25252529%25252520Historical%25252520Prices%25252520%25252526%25252520Data%25252520-%25252520NASDAQ.com%252526pidt%25253D1%252526oid%25253Djavascript%2525253AgetQuotes%25252528true%25252529%2525253B%252526ot%25253DA%252526oi%25253D898%3B; NSC_W.TJUFEFGFOEFS.OBTEBR.80=ffffffffc3a08e3745525d5f4f58455e445a4a423660; __atuvc=5%7C26

__VIEWSTATE=vrdXsfBP2CJNWK4qdpzeDQ%2B85IYYgny7JkJYNc%2F3LaENWzOHiJW05WwMwTsOS7lz3jxV2h%2FQWE0JiUa2EbHDcTMVVTPixtTnlCXdTmZJglCj8ENYrGrMRlQJ3ZiX7Bp2%2Fgos2pw6fVLkRKq5QwDuqfzPd9N7T%2FqqIkg0pMJWXi6XFLwU8hgmOMiK7TCpvWg0tlE9Qk0Syk26AlbkmAcTb4Js%2FcE2G1L0j%2FrnbficD2aJCYrLVtUp5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5d%7Ctrue%7CAA

Response

HTTP/1.0 200 OK
Content-Type: application/octet-stream; charset=utf-8
Content-Disposition: attachment; filename=HistoricalQuotes.csv
X-Powered-By: ASP.NET
Content-Length: 377
Expires: Sun, 30 Jun 2013 03:17:04 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Sun, 30 Jun 2013 03:17:04 GMT
Set-Cookie: NSC_W.TJUFEFGFOEFS.OBTEBR.80=ffffffffc3a08e3745525d5f4f58455e445a4a423660;expires=Sun, 30-Jun-2013 03:27:04 GMT;path=/;httponly
X-Cache: MISS from NORRX0200Bay11
X-Cache-Lookup: MISS from NORRX0200Bay11:10088
Via: 1.0 NORRX0200Bay11 (squid/3.1.14)
Connection: close

"date","close","volume","open","high","low"

"2013/06/28","7.8200","14525620.0000","7.8300","7.8800","7.7800"
"2013/06/27","7.8700","13891800.0000","7.8000","7.8700","7.7600"
"2013/06/26","7.7500","23732700.0000","7.9600","7.9600","7.7200"
"2013/06/25","7.9200","16871440.0000","7.8700","7.9300","7.8300"
"2013/06/24","7.7900","29888500.0000","7.9600","7.9700","7.7050"

-


I'd like to get the csv file downloaded using WinHTTP, but the main purpose of this is to learn how to use WinHTTP.

Share this post


Link to post
Share on other sites
trancexx

So that getQuotes() sets form field automatically based on symbol and time period for which you want the data for. This works fine for me:

#include "Winhttp.au3"


Local $sOut = DownloadThatThing("AA", "5d")

ConsoleWrite("!ERROR = " & @error & @CRLF)
ConsoleWrite("+>$sOut : " & @CRLF & $sOut & @CRLF & @CRLF)
;~ MsgBox(4096, "Response", StringFormat($sOut))


Func DownloadThatThing($sSymbol, $sTimePeriod = "3m")

    ; Initialize and get session handle
    Local $hOpen = _WinHttpOpen()
    ; Get connection handle
    Local $hConnect = _WinHttpConnect($hOpen, "www.nasdaq.com")

    ; Fill the form (id of the form is -getFile-)
    Local $sHTML = _WinHttpSimpleFormFill($hConnect, "symbol/" & $sSymbol & "/historical", "getFile", _
            "quotes_content_left_submitString", $sTimePeriod & "|true|" & $sSymbol) ; <- filling only this (thre rest is left default)

    Local $iErr = @error ; collect error

    ; Close handles
    _WinHttpCloseHandle($hConnect)
    _WinHttpCloseHandle($hOpen)

    ; Return whatever the result
    Return SetError($iErr, 0, $sHTML)
EndFunc
Edited by trancexx

♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites
big_daddy

That was less complicated than I thought. Thank you for the help.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Ascer
      By Ascer
      Hello
      Opertation Sys: Win7 x64
      Problem: Connecting to webs using TLS 1.1 +
      Description: WinHttp.WinHttpRequest.5.1 using TLS 1.0 by default, i need higher version to connect into some webs.
      Dim $oHttp = ObjCreate("WinHTTP.WinHTTPRequest.5.1") $oHttp.open ("GET", "https://howsmyssl.com/a/check", False) $oHttp.Option(9) = 128 ; 128 - TLS 1.0, 512 - TLS 1.1, 2048 - TLS 1.2, 2056 - TLS 1.1 & TLS 1.2 $oHttp.Send ConsoleWrite($oHttp.responseText & @CRLF) ; at end of the respond you can check your TLS version. Mine is: {"tls_version":"TLS 1.0","rating":"Bad"} Error: $oHttp.Option works only with parameter 128 (TLS 1.0) other values make error {Bad parameter}
      Additional: I've done this tutorial about enabling TLS in registry: <link>
      Thanks for support.
      Ascer
    • islandspapand
      By islandspapand
      Hi All
      i am currently trying to add a function to my project that can send SMS, i have gone with Twilio for the sms service that use a REST API.
      I have never worked with an API before, and could use some help.
      I can get my function working with using cURL.exe and copy past command from the website with the following code. And thats great unfortunately i am have issue with character like æøå when sending a SMS appears like a box or ?. this does not happen if i do it from the website so it looks like a Unicode issue in curl.exe.
      I have done some searching on the forum and understand that i should be able to implement this curl command with the WinHTTP UDF from @trancexx so i don't need a third part exe and it might fix my charater issue.
      Unfortunately i really don't understand how i am to change curl commands to the WinHTTP and i was hoping some good maybe give me an example i could learn from.
      Thanks in advanced
      i have removed the AuthToken number from the script.
      _SendSMS("00000000","SomeOne","SMS body info") Func _SendSMS($SendTo,$SendFrom,$Msgtxt) $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc" $AuthToken = "Auth Token number" $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _ '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&'' ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data) ;~ curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \ ;~ --data-urlencode 'To=+4500000000' \ ;~ --data-urlencode 'From=Reception' \ ;~ --data-urlencode 'Body=Test Body' \ ;~ -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken] EndFunc  
       
    • jesus40
      By jesus40
      Hello friends, i have a working curl command that show informations about my account on binance.com, but_it dont work with autoit code without curl.exe.
      I want to do it without curl, because the whole process much Slower_ with StdoutRead (I want get the response in variable.)
      My Curl command in Autoit:
      This 2 are works, but_ i would like to do it without curl.exe
      $apikey="XYZ" sCommand = @ScriptDir & '\curl.exe -k -H "X-MBX-APIKEY: ' & $apikey & '" -X GET "https://api.binance.com/api/v3/account?' & $request the same in .bat  file
      curl.exe -k -H "X-MBX-APIKEY: XYZ" -X GET "https://api.binance.com/api/v3/account?timestamp=1514917812000&signature=85bdee77e53cd521e1d5229fbfb459d53799c42b3fa4596d73f1520fad5f965a" (I use curl with -k option which allows curl to make insecure connections, because there is problem with the sites certificate, (cURL error 60))
       
      I tried many variations, this is the latest... I cant get the same response.
      curl $error message (I changed ): {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}
      autoit version $error message (Response code:400): Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed.
       
      $request = $query & '&signature=' & $signature $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://api.binance.com/api/v3/account", False) $oHTTP.SetRequestHeader("X-MBX-APIKEY", $apikey) $oHTTP.Send($request) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then MsgBox(4096, "Response code", $oStatusCode) EndIf  
      thanks
    • AlwaysLearning
      By AlwaysLearning
      Hello,
      I have been struggling with this for nearly 20 hours, and I just cannot seem to figure out the formatting for the header request.
      To test this, you will need to use this api key I set up for your testing purposes. (note, I sent tracexx a direct message about this as I didn't realize I could limit API restrictions until just now, so I am now hoping on of you may have the answer on hand)
      I need to be able to GET balance and POST orders.
      Right now, I can't get past the 401/403 errors on my own.
      I believe the Content is formatted for JSON, but using the JSON format didn't work for me ( although that may be because I'm an idiot and formatted something wrong).
      I want to get:
      GET balance page POST delete order page Here is a temporary API key + Secret API key with only the "View Balance Page" and "Delete Order" functions enabled:
      Access-key: tq6GeUrEvfxyF-LG
      Secret Access-Key: cZlz75K1wb8-Ed67pRaXvUWTPW6RTH9q

      Here is the site's API guide (I followed this closely and doubt the error is there): https://coincheck.com/documents/exchange/api#libraries
       
      And here is running source code (needs those keys inputted) which will hash the above keys to the required HMAC SHA256:
      #include <Crypt.au3> #include<WinHttp.au3> Global Const $CALG_SHA_256 = 0x0000800c ;; ===== $api = "/api/accounts/balance" $accessNonCE = _TimeGetStamp() $url = "https://coincheck.com/api/accounts/balance" $body = "" WinHTTP($url, $body) Func WinHTTP($sUrl, $sBody) Local $hOpen = _WinHttpOpen() Local $hConnect = _WinHttpConnect($hOpen, "https://coincheck.com/api/accounts/balance") ; Specify the reguest: ;Local $hRequest = _WinHttpOpenRequest($hConnect, Default, $sApi) $accessKey = "" ;; Add the key from above $secretKey = "" ;; Add the secret key from above $message = $accessNonCE & $sUrl $BinarySignature = HMAC($secretKey, $message) $signature = _Base64Encode($BinarySignature) ;Encode signature Local $hRequest = _WinHttpOpenRequest($hConnect, "GET") _WinHttpAddRequestHeaders($hRequest, 'ACCESS-KEY: '&$accessKey) _WinHttpAddRequestHeaders($hRequest, 'ACCESS-NONCE: '&$accessNonCE) _WinHttpAddRequestHeaders($hRequest, 'ACCESS-SIGNATURE: '&$signature) ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Local $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header Local $sData = _WinHttpReadData($hRequest) ; Clean _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ; Display retrieved data MsgBox(0, "Data", $sData) EndFunc Func sha256($message) Return _Crypt_HashData($message, $CALG_SHA_256) EndFunc Func HMAC($key, $message, $hash="sha256") Local $blocksize = 64 Local $a_opad[$blocksize], $a_ipad[$blocksize] Local Const $oconst = 0x5C, $iconst = 0x36 Local $opad = Binary(''), $ipad = Binary('') $key = Binary($key) If BinaryLen($key) > $blocksize Then $key = Call($hash, $key) For $i = 1 To BinaryLen($key) $a_ipad[$i-1] = Number(BinaryMid($key, $i, 1)) $a_opad[$i-1] = Number(BinaryMid($key, $i, 1)) Next For $i = 0 To $blocksize - 1 $a_opad[$i] = BitXOR($a_opad[$i], $oconst) $a_ipad[$i] = BitXOR($a_ipad[$i], $iconst) Next For $i = 0 To $blocksize - 1 $ipad &= Binary('0x' & Hex($a_ipad[$i],2)) $opad &= Binary('0x' & Hex($a_opad[$i],2)) Next Return Call($hash, $opad & Call($hash, $ipad & Binary($message))) EndFunc Func _TimeGetStamp() Local $av_Time $av_Time = DllCall('CrtDll.dll', 'long:cdecl', 'time', 'ptr', 0) If @error Then SetError(99) Return False EndIf Return $av_Time[0] EndFunc Func _Base64Encode($input) $input = Binary($input) Local $struct = DllStructCreate("byte[" & BinaryLen($input) & "]") DllStructSetData($struct, 1, $input) Local $strc = DllStructCreate("int") Local $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _ "ptr", DllStructGetPtr($struct), _ "int", DllStructGetSize($struct), _ "int", 1, _ "ptr", 0, _ "ptr", DllStructGetPtr($strc)) If @error Or Not $a_Call[0] Then Return SetError(1, 0, "") ; error calculating the length of the buffer needed EndIf Local $a = DllStructCreate("char[" & DllStructGetData($strc, 1) & "]") $a_Call = DllCall("Crypt32.dll", "int", "CryptBinaryToString", _ "ptr", DllStructGetPtr($struct), _ "int", DllStructGetSize($struct), _ "int", 1, _ "ptr", DllStructGetPtr($a), _ "ptr", DllStructGetPtr($strc)) If @error Or Not $a_Call[0] Then Return SetError(2, 0, ""); error encoding EndIf Return DllStructGetData($a, 1) EndFunc ;==>_Base64Encode
       
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.