Jump to content
Sign in to follow this  
big_daddy

Using WinHTTP to POST and Receive File

Recommended Posts

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%2FrnbficD2aJCYrLVtUp5zkns7Qzt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ctrue%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

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

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  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Colduction
      Hi AutoIt Members and Programmers, i have a problem with Telegram UDF that does not work on some of my servers, Telegram is not restricted in these machines, here is console output in Windows 7 (Server):
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" /UserParams +>20:20:40 Starting AutoIt3Wrapper (19.1127.1402.0} from:SciTE.exe (4.2.0.0) Keyboard:00000429 OS:WIN_7/Service Pack 1 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3 +>20:20:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Test file for Telegram UDF (https://github.com/xLinkOut/telegram-udf-autoit). This file need a valid ChatID of a Telegram user who has already sent at least a message to the bot, and a valid token given by @BotFather. Insert this data in the source code. "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\src\Telegram.au3" (1098) : ==> The requested action with this object has failed.: $oHTTP.Send() $oHTTP^ ERROR ->20:20:41 AutoIt3.exe ended.rc:1 +>20:20:41 AutoIt3Wrapper Finished. >Exit code: 1 Time: 1.56 It's really annoying problem in WinHTTP
    • By nacerbaaziz
      goodmorning autoit team
      today am comming with some winhttp problems, i hope that you can help me to solve them.
      the first problem
      is when opening a request
      my forums api allow me to delete any post using the api key
      all functions work, i mean post / get
      but when i tried to use the delete verb it's gave me an html 404 error
      here is what am tried
      #include "WinHttp.au3" ; Open needed handles Global $hOpen = _WinHttpOpen() Global $hConnect = _WinHttpConnect($hOpen, "xxxxxxxx.com") ; Specify the reguest: Global $hRequest = _WinHttpOpenRequest($hConnect, "Delete", "/vb/Api/posts/10447/?hard_delete=true", default, default) _WinHttpAddRequestHeaders($hRequest, "XF-Api-Key:xxxxx") _WinHttpAddRequestHeaders($hRequest, "XF-Api-User:xxxxx") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Global $sHeader = 0, $sReturned = 0 ; If there is data available... If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_DISPOSITION) ;Or maybe: ; $sHeader = _WinHttpQueryHeaders($hRequest, BitOR($WINHTTP_QUERY_RAW_HEADERS_CRLF, $WINHTTP_QUERY_CUSTOM), "Content-Disposition") Do $sReturned &= _WinHttpReadData($hRequest) Until @error msgBox(64, "", $sReturned) endIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen)  
      and here is the error message
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /vb/Api/posts/10447/ on this server.<br /> </p> </body></html>  
      i hope you can help me 
      thanks in advance
    • By Roy_
      Ciao,
      This example reproduces the problem I encounter when sending a post request to an echo server.
      Instead of being sent as text utf8, the data is transmitted base64 encoded.
      Example:
      - json String: '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}'
      - server response: "data:application/octet-stream;base64,AAAAALgE6QNYAIAAAgAAANQCAAAAAAAAWF8AAAAAAAD0VQAAAAAAAD9APQAAAAAAAwAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAABBAAAAAAABRUAAAAmIZwcAbRt8/LMa9UAAAAAAAAAAGFzIGlkIHRlbXB1cyBtaS4gTW9yYmkgaXBzdW0gZW5pbSwgdWx0cmljaWVzIGFjIGF1Z3VlIHNpdCBhbWV0LCB1bGxhbWNvcnBlciBmaW5pYnVzIGV4LiBWZXN0aWJ1bHVtIHZlbCBwb3N1ZXJlIG5pYmgsIG5lYyBmYXVjaWJ1cyBlcm9zLiBOYW0gbWFsZXN1YWRhIG5vbiBsYWN1cyBhIHN1c2NpcGl0LiBOdWxsYSByaG9uY3VzIHRlbXB1cyBtaSBxdWlzIHBsYWNlcmF0LiBDdXJhYml0dXIgY29tbW9kbyB0aW5jaWR1bnQganVzdG8gcXVpcyBzb2xsaWNpdHVkaW4uIn0="
       
      How can I go about transmitting data in text format utf8?
      Thanks in advance for the help.
      In the zip file:
      - CurlJsonPost.au3: this script
      - Curl.au3: UDF by Ward (thank you!)
      - data.json: json srting for command line test
       
      Note: using Curl.exe with json string saved in a file (utf8 encoded) named data.json, works perfectly
      To try with the command line tool:
      - save data.json in curl\bin directory
      - open cmd.exe and cd to curl\bin directory
      - Enter the following command:
      curl -H "Content-Type: application/json" --data @data.json https://httpbin.org/post
       
      #Include "Curl.au3" Global $_cURL_OutputBuffer Local $sJson = '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}' Local $iRetCode, $sServerResponse ConsoleWrite("=== Json post test ===" & @LF) ConsoleWrite(StringFormat("Retcode: %s - %s", $iRetCode, Curl_Easy_strerror($iRetCode)) & @LF) ConsoleWrite("Data returned from server" & @LF & @LF) $sServerResponse = JsonPost_Test($sJson, $iRetCode) ConsoleWrite($sServerResponse & @LF) Func JsonPost_Test($sJson, ByRef $iRetCode) ; Init Easy Curl Interface e set url (echo service) Local $oCurl = Curl_Easy_Init() curl_easy_setopt($oCurl, $CURLOPT_URL, "https://httpbin.org/post") ; Set content type header Local $headers = curl_slist_append(0, "Content-Type: application/json") curl_easy_setopt($oCurl, $CURLOPT_HTTPHEADER, $headers) ; Post fields & size curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDS, $sJson) curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDSIZE, StringLen($sJson)) ; Set callbac function to get server response back (see global var $_cURL_OutputBuffer) $hWriteFunc = DllCallbackRegister("WriteFunc_CallBack", "uint:cdecl", "ptr;uint;uint;ptr") curl_easy_setopt($oCurl, $CURLOPT_WRITEFUNCTION, DllCallbackGetPtr($hWriteFunc)) ; Ignore ssl certificates check curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYPEER, 0) curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYHOST, 0) ; Execute the post request $iRetCode = curl_easy_perform($oCurl) ; Set return trasfer & clear output buffer global var Local $sReturnTransfer = $_cURL_OutputBuffer $_cURL_OutputBuffer = "" Return SetError(0, 0, $sReturnTransfer) EndFunc Func WriteFunc_CallBack($ptr,$nSize,$nMemb,$pStream) Local $vData = DllStructCreate ("byte[" & $nSize*$nMemb & "]",$ptr) $_cURL_OutputBuffer &= BinaryToString(DllStructGetData($vData,1)) Return $nSize*$nMemb EndFunc  
      curlJsonPost.zip
    • By Melque_Lima
      A little help here please !?
      I'm trying to parse a file but the function is not working well! i think there is some thind doing wrong at FileRead()
      Obs: username,password and API link below is fictitious
      ConsoleWrite(">POST METHOD UPLOADING LOCAL IMAGE<" & @CRLF) _PostMethodTest() Func _PostMethodTest() Local Const $sAPIKey = '8f1e0a750088957' Local $sBoundary = "--------Boundary" Local $sHeaders = "Content-Type: multipart/form-data; boundary=" & $sBoundary & @CRLF Local $sData = '' Local $sFileName="image.jpg" Local $sFilePath="C:\Users\DELL\Desktop\" & $sFileName Local $hFile=FileOpen($sFilePath,16);16=$FO_BINARY Local $sFileData=FileRead($hFile) FileClose($hFile) $sData &= "--" & $sBoundary & @CRLF $sData &= 'Content-Disposition: form-data; name="myImage"; filename="' & $sFileName & '"' & @CRLF $sData &= 'Content-Type: application/upload' & @CRLF & @CRLF $sData &= BinaryToString($sFileData,0) & @CRLF $sData &= "--" & $sBoundary & @CRLF $sData &= 'Content-Disposition: form-data; name="username"' & @CRLF & @CRLF $sData &="myuserName" & @CRLF $sData &= "--" & $sBoundary & @CRLF $sData &= 'Content-Disposition: form-data; name="password"' & @CRLF & @CRLF $sData &="MyPassword" & @CRLF $sData &=$sBoundary & "--" ConsoleWrite($sData) Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", "http://myapi", False) $oHTTP.SetRequestHeader("Content-Type", "multipart/form-data; " & "boundary=" & $sBoundary) $oHTTP.SetRequestHeader("apikey", $sAPIKey) $oHTTP.Send(StringToBinary($sData,1)) Local $sReceived = $oHTTP.ResponseText ConsoleWrite($sReceived & @CRLF) EndFunc ;==>_PostMethodTest  

    • By Surya
      Hi everyone its been loooong since I posted here 
      I have been trying to convert this curl executable parameters into autoit using the winhttp com object;
      curl -F data_file=@my_audio_file.mp3 -F model=en-US "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4jdsgjhgghstOGU5YS00OWFhLWghdgjshgdhbshj017###" any ideas guys
       
      PS: I am excited to post here after a looong time
×
×
  • Create New...