Jump to content

Recommended Posts

Posted
Posted (edited)

Good to hear I inspired you! Would you mind giving an example? Like sending a POST with these parameters

user=admin

pass=admin

post data: restart=Restart?

http://www.autoitscript.com/forum/index.php?showtopic=83971

Or does WinHTTP still need some work in order to accomplish this?

Try this:

#include "WinHTTP.au3"


$LocalIP = "192.168.3.1" 

$hw_open = _WinHttpOpen()

$hw_connect = _WinHttpConnect($hw_open, $LocalIP)

$h_openRequest = _WinHttpOpenRequest($hw_connect, "POST", "restart.cgi")

_WinHttpSetCredentials($h_openRequest, $WINHTTP_AUTH_TARGET_SERVER, $WINHTTP_AUTH_SCHEME_BASIC, "admin", "admin")

_WinHttpSendRequest($h_openRequest)

_WinHttpWriteData($h_openRequest, "restart=Restart?")

_WinHttpReceiveResponse($h_openRequest)

_WinHttpCloseHandle($h_openRequest)

_WinHttpCloseHandle($hw_connect)

_WinHttpCloseHandle($hw_open)




Func _WinHttpWriteData($hRequest, $string)
    
    Local $dwNumberOfBytesToWrite = StringLen($string)  
    
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpWriteData", _
            "hwnd", $hRequest, _
            "str", $string, _
            "dword", $dwNumberOfBytesToWrite, _
            "ptr", 0)
    
    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, -1)
    EndIf

    Return SetError(0, 0, $a_iCall[0])
    
    
EndFunc   ;==>_WinHttpWriteData

That script have _WinHttpWriteData() that is not in WinHTTP.au3 (I wasn't sure about "str" or "wstr" in dll call).

Edited by trancexx

♡♡♡

.

eMyvnE

Posted (edited)

Well, the data type is not too important, because the Data will be sent binary i think. But if you want to send text, ANSI str should be right in most cases :mellow:

This page good for testing, i think :(http://www.snee.com/xml/crud/posttest.html

//Edit: made an working example:) you also have to add the size to sendRewuest :)

#include "WinHTTP.au3"


$LocalIP = "www.snee.com"

$hw_open = _WinHttpOpen()

$hw_connect = _WinHttpConnect($hw_open, $LocalIP)

$h_openRequest = _WinHttpOpenRequest($hw_connect, "POST", "xml/crud/posttest.cgi?sgs")

;~ _WinHttpSetCredentials($h_openRequest, $WINHTTP_AUTH_TARGET_SERVER, $WINHTTP_AUTH_SCHEME_BASIC, "admin", "admin")

$data = "fname=Rghgt&lname=345"

_WinHttpSendRequest($h_openRequest,$WINHTTP_NO_ADDITIONAL_HEADERS, 0, $WINHTTP_NO_REQUEST_DATA, 0, StringLen($data), 0)

_WinHttpWriteData($h_openRequest, $data)

_WinHttpReceiveResponse($h_openRequest)

MsgBox(0, 'Recived', _WinHttpReadData($h_openRequest))

_WinHttpCloseHandle($h_openRequest)

_WinHttpCloseHandle($hw_connect)

_WinHttpCloseHandle($hw_open)




Func _WinHttpWriteData($hRequest, $string)
   
    Local $dwNumberOfBytesToWrite = StringLen($string) 
   
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpWriteData", _
            "hwnd", $hRequest, _
            "str", $string, _
            "dword", $dwNumberOfBytesToWrite, _
            "dword*", 0)
   
    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, -1)
    EndIf

    Return SetError(0, 0, $a_iCall[0])
   
   
EndFunc   ;==>_WinHttpWriteData
Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Posted

I think a wrapper for these functions would be helpful... here's my untested take on it

Func WinHttpWrapper($URL, $Type, $Data = "", $username = "", $password = "", $protocall = "HTTP/1.1")
    $temp = SplitURL($URL)
    $Server = $temp[0]
    $Address = $temp[1]
    $hw_open = _WinHttpOpen("WinHTTP Example")
    $hw_connect = _WinHttpConnect($hw_open, $Server)
    $h_openRequest = _WinHttpOpenRequest($hw_connect, $Type, $Address, $protocall)
    _WinHttpSetCredentials($h_openRequest, $WINHTTP_AUTH_TARGET_SERVER, $WINHTTP_AUTH_SCHEME_BASIC, $username, $password)
    _WinHttpSendRequest($h_openRequest)
    _WinHttpWriteData($h_openRequest, $Data)
    $Response = _WinHttpReceiveResponse($h_openRequest)
    _WinHttpCloseHandle($h_openRequest)
    _WinHttpCloseHandle($hw_connect)
    _WinHttpCloseHandle($hw_open)
    Return $Response
EndFunc

Func SplitURL($URL)
    Dim $array[2]
    $split = SplitURLHelper($URL, 3)
    If $split == 0 Then
        $split = SplitURLHelper($URL, 2)
        $URL = StringRight($URL, $split)
        $array[0] = $URL
        Return $array
    EndIf
    
    $left = StringLeft($URL, $split)
    $right = StringRight($URL, $split)
    
    $split = SplitURLHelper($left, 2)
    $left = StringRight($left, $split)
    
    $array[0] = $left
    $array[1] = $right
    Return $array
EndFunc

Func SplitURLHelper($String, $pos)
    $split = StringInStr($String, "/", 0, $pos)
    If $split == 0 Then
        $split = StringInStr($String, "\", 0, $pos)
    EndIf
    Return $split
EndFunc
Posted (edited)

Well, the data type is not too important, because the Data will be sent binary i think. But if you want to send text, ANSI str should be right in most cases :mellow:

Yes, ok.

"ptr" to "dword*"?

That parameter is set to 0.

I have made a modification or two to _WinHttpSendRequest() to meat* another (original actually) way of sending aditional data to the sever.

New (modified) _WinHttpSendRequest():

; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpSendRequest
; Description ...: Sends the specified request to the HTTP server.
; Syntax.........: _WinHttpSendRequest($hRequest [, $pwszHeaders [, $sOptional [, $dwTotalLength [, $dwContext]]]])
; Parameters ....: $hRequest - Handle returned by _WinHttpOpenRequest().
; $pwszHeaders - String that contains the additional headers to append to the request. Default is $WINHTTP_NO_ADDITIONAL_HEADERS.
; $sOptional - String that contains any optional data to send immediately after the request headers. Default is $WINHTTP_NO_REQUEST_DATA.
; $dwTotalLength - An unsigned long integer value that contains the length, in bytes, of the total optional data sent. Default is 0.
; $dwContext - A pointer to a pointer-sized variable that contains an application-defined value that is passed, with the request handle, to any callback functions. Default is 0.
; Return values .: Success - Returns 1.
; - Sets @error to 0
; Failure - Returns -1 and sets @error:
; |1 - DllCall failed.
; Author ........: trancexx
; Modified.......:
; Remarks .......: Specifying optional data ($sOptional) will cause $dwTotalLength to receive the size of that data if left default value.
; Related .......:
; Link ..........; http://msdn.microsoft.com/en-us/library/aa384110(VS.85).aspx
; Example .......; Yes
;
;==========================================================================================
Func _WinHttpSendRequest($hRequest, $pwszHeaders = $WINHTTP_NO_ADDITIONAL_HEADERS, $sOptional = $WINHTTP_NO_REQUEST_DATA, $dwTotalLength = 0, $dwContext = 0)

    Local $iOptionalLength = StringLen($sOptional)
    Local $structOptional = DllStructCreate("char[" & $iOptionalLength + 1 & "]")
    DllStructSetData($structOptional, 1, $sOptional)

    If Not $dwTotalLength Or $dwTotalLength < $iOptionalLength Then
        $dwTotalLength += $iOptionalLength
    EndIf
    
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpSendRequest", _
            "hwnd", $hRequest, _
            "wstr", $pwszHeaders, _
            "dword", 0, _
            "ptr", DllStructGetPtr($structOptional), _
            "dword", $iOptionalLength, _
            "dword", $dwTotalLength, _
            "ptr", $dwContext)

    If @error Or Not $a_iCall[0] Then
        SetError(1, 0, 0)
    EndIf
    
    Return SetError(0, 0, 1)

EndFunc ;==>_WinHttpSendRequest

@mikeytown2; I can see how can (could) that be useful.

edit: meat* = meet

Edited by Jon

♡♡♡

.

eMyvnE

Posted (edited)

I'm having problems with this six functions:

No5. WinHttpCrackUrl

No6. WinHttpCreateUrl

...l

No23. WinHttpSetStatusCallback

No27. WinHttpWriteData

WinHttpWriteData has been translated by trancexx and me.

Now, i#ll post WinHttpCrackUrl, WinHttpCreateUrl and WinHttpSetStatusCallback :mellow:

(examples in the files)

WinHTTP_CrackURL.au3

WinHTTPSetStatusCallback.au3

Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Posted (edited)

i played a bit with it but could not figure out how to send cookies correctly, any idea?

EDIT:

saw that it handeles cookies automatically GREAT...

now i just have to figure out why i still can't login ....

EDIT2: HEEEEEELLLLLPPPPPPPP

tried everything even fighting through msdn KB but can't figure out how to send a simple post request with a pin=123456 attribut, so that it will allow me to logon :mellow:

with the old winhttp udf powered by tcp open .... it was solved as this:

_HTTPPost('', $sessionid2, '', $fax_device & ":8000", '/login', $socket, 'pin=98765&uri=%2Frps%2F_top.htm')

any nice help appreciated :-)

Edited by JRSmile
$a=StringSplit("547275737420796F757220546563686E6F6C75737421","")
For $b=1 To UBound($a)+(-1*-1*-1)step(2^4/8);&$b+=1*2/40*µ&Asc(4)
Assign("c",Eval("c")&Chr(Dec($a[$b]&$a[$b+1])));''Chr("a")&"HI"
Next ;time_U&r34d,ths,U-may=get$the&c.l.u.e;b3st-regards,JRSmile;
MsgBox(0x000000,"",Eval("c"));PiEs:d0nt+*b3.s4d.4ft3r.1st-try:-)
Posted (edited)

WinHttpWriteData has been translated by trancexx and me.

Now, i#ll post WinHttpCrackUrl, WinHttpCreateUrl and WinHttpSetStatusCallback :mellow:

(examples in the files)

Now that's what I'm talking about!

Will add that functions to first post attachments (after I modify them just a bit, hope you wouldn't mind - style differences)

edit:

I like the way you sized the structures in _WinHttpCrackUrl() and stripped output afterwards

Edited by trancexx

♡♡♡

.

eMyvnE

Posted (edited)

This may come in handy as I've been trying to do HTTP functions (file download) with this UDF WinINet.au3 (FTP/HTTP/HTTPS/Gopher+)

Now, I'm wondering what your thoughts about using WinInet over WinHTTP, WinINet seems more robust as it also includes functions for FTP, HTTPS, and Gopher+. Your UDF; WinHTTP is more tailored for HTTP. I want to know, does it contain more functions for HTTP? Is it faster, what's the reason for reinventing the wheel?

Microsoft insist on making development an arms length in becoming dependent on Tylenol pills. :mellow:

Edited by mrRevoked
Don't bother, It's inside your monitor!------GUISetOnEvent should behave more like HotKeySet()
Posted

Now that's what I'm talking about!

Will add that functions to first post attachments (after I modify them just a bit, hope you wouldn't mind - style differences)

edit:

I like the way you sized the structures in _WinHttpCrackUrl() and stripped output afterwards

You can modify them as much as you want :mellow: I just wanted to create examples, so the code isn't written perfectly... You should also create documentaion for the funcs.

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Posted

This may come in handy as I've been trying to do HTTP functions (file download) with this UDF WinINet.au3 (FTP/HTTP/HTTPS/Gopher+)

Now, I'm wondering what your thoughts about using WinInet over WinHTTP, WinINet seems more robust as it also includes functions for FTP, HTTPS, and Gopher+. Your UDF; WinHTTP is more tailored for HTTP. I want to know, does it contain more functions for HTTP? Is it faster, what's the reason for reinventing the wheel?

Microsoft insist on making development an arms length in becoming dependent on Tylenol pills. :mellow:

castoff?

Advantages or disadvantages of this or that are yet to be determined.

This is not reinventing the wheel, but offering another option. Something like this:

Beep(400, 200)
DllCall("msvcrt.dll", "int:cdecl", "_beep", "int", 500, "int", 200)
DllCall("kernel32.dll","int", "Beep","int",600,"int",200)
DllCall("pncrt.dll", "int:cdecl", "_beep", "int", 700, "int", 200)

First post updated.

♡♡♡

.

eMyvnE

Posted

i played a bit with it but could not figure out how to send cookies correctly, any idea?

EDIT:

saw that it handeles cookies automatically GREAT...

now i just have to figure out why i still can't login ....

EDIT2: HEEEEEELLLLLPPPPPPPP

tried everything even fighting through msdn KB but can't figure out how to send a simple post request with a pin=123456 attribut, so that it will allow me to logon :mellow:

with the old winhttp udf powered by tcp open .... it was solved as this:

_HTTPPost('', $sessionid2, '', $fax_device & ":8000", '/login', $socket, 'pin=98765&uri=%2Frps%2F_top.htm')

any nice help appreciated :-)

Just post script with calling _HTTPPost() properly and we'll find the solution, I'm sure.

Few examples using WinHTTP.au3 functions.

#include "WinHTTP.au3"
#include <Array.au3>


;Checking platform:
If _WinHttpCheckPlatform() Then
    MsgBox(0, "WinHTTP checking platform result", "Platform supported")
Else
    MsgBox(0, "WinHTTP checking platform result", "Platform not supported!")
EndIf

; Date and time according to the HTTP version 1.0 specification:
MsgBox(0, "Date and time according to the HTTP version 1.0 specification", _WinHttpTimeFromSystemTime())

; Transforming HTTP/1.0 time format to sistem time format:
$time_array = _WinHttpTimeToSystemTime("Fri, 07 Nov 2010 20:42:16 GMT")
_ArrayDisplay($time_array, "_WinHttpTimeToSystemTime()")

; Cracking URL:
$URL_array = _WinHttpCrackUrl("http://www.autoitscript.com/forum/index.php?showforum=9")
_ArrayDisplay($URL_array, "_WinHttpCrackUrl()")

; Creating URL out of array of components:
Global $URL_array[8] = ["http", 1, "www.autoitscript.com", 80, "Jon", "deadPiXels", "admin.php"]
MsgBox(0, "Created URL", _WinHttpCreateUrl($URL_array))

♡♡♡

.

eMyvnE

Posted (edited)

Found some problems, if using String as Datatype for ReadData. This does not work, if HTML is in UTF-8 :mellow:

So i made some funcs using byte Structures, which you can convert with BinaryToString. Create Binary with StringToBinary;)

; Prog@ndy
; reads complete HTML response in ASCII and UTF-8 encoding.
Func _WinHttpReadHTML($hRequest)
    Local $data
    While 1
        $chunk = _WinHttpReadDataBin($hRequest)
        If @error <> 0 Then ExitLoop
        $data = _BinaryConcat($data, $chunk)
    WEnd
    $Content_Type = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_TYPE)
    Select
        Case StringInStr($Content_Type, "charset=UTF-8")
            $data = BinaryToString($data, 4)
        Case Else
            $data = BinaryToString($data)
    EndSelect
    Return $data
EndFunc   ;==>_WinHttpReadHTML

; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpSendRequestBin
; Description ...: Sends the specified request to the HTTP server.
; Syntax.........: _WinHttpSendRequest($hRequest [, $sHeaders [, $sOptional [, $iTotalLength [, $iContext]]]])
; Parameters ....: $hRequest - Handle returned by _WinHttpOpenRequest().
;                  $sHeaders - String that contains the additional headers to append to the request. Default is $WINHTTP_NO_ADDITIONAL_HEADERS.
;                  $sOptional - Binary Data that contains any optional data to send immediately after the request headers. Default is $WINHTTP_NO_REQUEST_DATA.
;                  $iTotalLength - An unsigned long integer value that contains the length, in bytes, of the total optional data sent. Default is 0.
;                  $iContext - A pointer to a pointer-sized variable that contains an application-defined value that is passed, with the request handle, to any callback functions. Default is 0.
; Return values .: Success - Returns 1.
;                          - Sets @error to 0
;                  Failure - Returns -1 and sets @error:
;                  |1 - DllCall failed.
; Author ........: trancexx
; Modified.......:
; Remarks .......: Specifying optional data ($sOptional) will cause $iTotalLength to receive the size of that data if left default value.
; Related .......:
; Link ..........; http://msdn.microsoft.com/en-us/library/aa384110(VS.85).aspx
; Example .......; Yes
;
;==========================================================================================
Func _WinHttpSendRequestBin($hRequest, $sHeaders = $WINHTTP_NO_ADDITIONAL_HEADERS, $sOptional = $WINHTTP_NO_REQUEST_DATA, $iTotalLength = 0, $iContext = 0)

    Local $iOptionalLength = BinaryLen($sOptional)
    Local $structOptional = DllStructCreate("byte[" & $iOptionalLength & "]")
    DllStructSetData($structOptional, 1, $sOptional)

    If Not $iTotalLength Or $iTotalLength < $iOptionalLength Then
        $iTotalLength += $iOptionalLength
    EndIf
    
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpSendRequest", _
            "hwnd", $hRequest, _
            "wstr", $sHeaders, _
            "dword", 0, _
            "ptr", DllStructGetPtr($structOptional), _
            "dword", $iOptionalLength, _
            "dword", $iTotalLength, _
            "ptr", $iContext)

    If @error Or Not $a_iCall[0] Then
        SetError(1, 0, 0)
    EndIf
    
    Return SetError(0, 0, 1)

EndFunc   ;==>_WinHttpSendRequestBin
; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpWriteDataBin
; Description ...: Writes request data to an HTTP server.
; Syntax.........: _WinHttpWriteData($hRequest, $string)
; Parameters ....: $hRequest - Valid handle returned by _WinHttpSendRequest().
;                  $binary - Binary data to write.
; Return values .: Success - Returns 1
;                          - Sets @error to 0
;                          - sets @extended to written bytes
;                  Failure - Returns 0 and sets @error:
;                  |1 - DllCall failed.
; Author ........: trancexx, ProgAndy
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........; http://msdn.microsoft.com/en-us/library/aa384120(VS.85).aspx
; Example .......; Yes
;
;==========================================================================================
Func _WinHttpWriteDataBin($hRequest, $binary)
    Local $lpBinary
    Local $iNumberOfBytesToWrite
    If IsDllStruct($binary) Then
        $lpBinary = DllStructGetPtr($binary)
        $iNumberOfBytesToWrite = DllStructGetSize($binary)
    Else
        $iNumberOfBytesToWrite = BinaryLen($binary)
        Local $sBinary = DllStructCreate("byte[" & $iNumberOfBytesToWrite & "]")
        DllStructSetData($sBinary, 1, $binary)
        $lpBinary = DllStructGetPtr($binary)
    EndIf
    
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpWriteData", _
            "hwnd", $hRequest, _
            "ptr", $lpBinary, _
            "dword", $iNumberOfBytesToWrite, _
            "dword*", 0)
    
    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, 0)
    EndIf

    Return SetError(0, $a_iCall[4], 1)
    
    
EndFunc   ;==>_WinHttpWriteDataBin
; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpReadDataBin
; Description ...: Reads data from a handle opened by the _WinHttpOpenRequest() function.
; Syntax.........: _WinHttpReadData($hRequest [, $iNumberOfBytesToRead])
; Parameters ....: $hRequest - Valid handle returned from a previous call to _WinHttpOpenRequest().
;                  $iNumberOfBytesToRead - Integer value that contains the number of bytes to read. Default is 8192 bytes.
; Return values .: Success - Returns data read.
;                          - Sets @error to 0
;                  Failure - Returns empty string and sets @error:
;                  |1 - DllCall failed.
; Author ........: trancexx
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........; http://msdn.microsoft.com/en-us/library/aa384104(VS.85).aspx
; Example .......; Yes
;
;==========================================================================================
Func _WinHttpReadDataBin($hRequest, $iNumberOfBytesToRead = 8192)

    Local $lpBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]")

    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpReadData", _
            "hwnd", $hRequest, _
            "ptr", DllStructGetPtr($lpBuffer), _
            "ulong", $iNumberOfBytesToRead, _
            "dword*", 0)

    Select
        Case @error Or Not $a_iCall[0]
            Return SetError(1)
        Case $a_iCall[4] = 0
            Return SetError(-1)
        Case $a_iCall[4] < $iNumberOfBytesToRead
            Return BinaryMid(DllStructGetData($lpBuffer, 1), 1, $a_iCall[4])
    EndSelect
    
    Return DllStructGetData($lpBuffer, 1)
    
EndFunc   ;==>_WinHttpReadDataBin
;===============================================================================
;
; Function Name:   _BinaryConcat
; Description::    Concatenates 2 binary Variables
; Parameter(s):    2 Binary variables, by reference
; Requirement(s):
; Return Value(s): New Binary data
; Author(s):       Prog@ndy
;
;===============================================================================
;
Func _BinaryConcat(ByRef $Binary1, ByRef $Binary2)
    Select
        Case IsBinary($Binary1) And Not IsBinary($Binary2)
            Return $Binary1
        Case Not IsBinary($Binary1) And IsBinary($Binary2)
            Return $Binary2
        Case Not (IsBinary($Binary1) And IsBinary($Binary2))
            Return SetError(1)
    EndSelect
    Local $Len1 = BinaryLen($Binary1), $Len2 = BinaryLen($Binary2)
    Local $s = DllStructCreate("byte[" & $Len1 & "];byte[" & $Len2 & "]")
    DllStructSetData($s, 1, $Binary1)
    DllStructSetData($s, 2, $Binary2)
    Return DllStructGetData(DllStructCreate("byte[" & $Len1 + $Len2 & "]", DllStructGetPtr($s)), 1)
EndFunc   ;==>_BinaryConcat
Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Posted

I wasn't experiencing that difficulties, and was aiming sites with different charsets deliberately.

Will test that.

I was pretty sure that I changed the last parameter of DllCall() in _WinHttpReadData() from "ptr" to "dword*" and throw it out as @extended.

This is not working for you?

#include "WinHTTP.au3"


Global $hw_open = _WinHttpOpen("WinHTTP Example")
If @error Then 
    MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
    Exit
EndIf

Global $hw_connect = _WinHttpConnect($hw_open, "msdn.microsoft.com")
If @error Then 
    MsgBox(48, "Error", "Error specifying the initial target server of an HTTP request.")
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

Global $h_openRequest = _WinHttpOpenRequest($hw_connect, "GET", "en-us/library/aa384104(VS.85).aspx")
If @error Then 
    MsgBox(48, "Error", "Error creating an HTTP request handle.")
    _WinHttpCloseHandle($hw_connect)
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

_WinHttpSendRequest($h_openRequest)
If @error Then 
    MsgBox(48, "Error", "Error sending the specified request.")
    _WinHttpCloseHandle($hw_connect)
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

_WinHttpReceiveResponse($h_openRequest)

If _WinHttpQueryDataAvailable($h_openRequest) Then
    Global $header = _WinHttpQueryHeaders($h_openRequest)
    ConsoleWrite($header & @CRLF & @CRLF)
    Global $data
    While 1
        $data &= X_WinHttpReadData($h_openRequest)
        If Not @extended Then ExitLoop      
    WEnd
    ConsoleWrite($data & @CRLF)
EndIf

_WinHttpCloseHandle($h_openRequest)
_WinHttpCloseHandle($hw_connect)
_WinHttpCloseHandle($hw_open)



Func X_WinHttpReadData($hRequest, $iNumberOfBytesToRead = 8192)

    Local $lpBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]")

    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpReadData", _
            "hwnd", $hRequest, _
            "ptr", DllStructGetPtr($lpBuffer), _
            "ulong", $iNumberOfBytesToRead, _
            "dword*", 0)
    
    If @error Or Not $a_iCall[0] Then
        SetError(1, 0, "")
    EndIf
    
    Return SetError(0, $a_iCall[4], DllStructGetData($lpBuffer, 1))
    
EndFunc

♡♡♡

.

eMyvnE

Posted (edited)

No. try on Autoit.de:

1) recieving Vorgänge instead of Vorgänge

2) have additional data at the end:

</html>
0

.

second problem can be fixed this way:

Func X_WinHttpReadData($hRequest, $iNumberOfBytesToRead = 8192)

    Local $lpBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]")

    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpReadData", _
            "hwnd", $hRequest, _
            "ptr", DllStructGetPtr($lpBuffer), _
            "ulong", $iNumberOfBytesToRead, _
            "dword*", 0)
   
    Select 
        Case @error Or Not $a_iCall[0]
            Return SetError(1, 0, "")
        Case Not $a_iCall[4]
            Return SetError(0, 0, "")
        Case $a_iCall[4] < $iNumberOfBytesToRead
            Return SetError(0, $a_iCall[4], StringLeft(DllStructGetData($lpBuffer, 1),$a_iCall[4]))
    EndSelect
   
    Return SetError(0, $a_iCall[4], DllStructGetData($lpBuffer, 1))
   
EndFunc

I propose to create two functions. One with char and another with Binary :mellow: So everyone can decide what he needs (e.g. if you want to download (upload) files, Binary is useful, too.)

Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

Posted

This is great! I think that we'll make something out of this :mellow:

About two functions...

Maybe just one, like this:

#include "WinHTTP.au3"


Global $hw_open = _WinHttpOpen()
If @error Then
    MsgBox(48, "Error", "Error initializing the usage of WinHTTP functions.")
    Exit
EndIf

Global $hw_connect = _WinHttpConnect($hw_open, "www.autoit.de")
If @error Then
    MsgBox(48, "Error", "Error specifying the initial target server of an HTTP request.")
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

Global $h_openRequest = _WinHttpOpenRequest($hw_connect)
If @error Then
    MsgBox(48, "Error", "Error creating an HTTP request handle.")
    _WinHttpCloseHandle($hw_connect)
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

_WinHttpSendRequest($h_openRequest)
If @error Then
    MsgBox(48, "Error", "Error sending the specified request.")
    _WinHttpCloseHandle($hw_connect)
    _WinHttpCloseHandle($hw_open)
    Exit
EndIf

_WinHttpReceiveResponse($h_openRequest)

If _WinHttpQueryDataAvailable($h_openRequest) Then
    Global $header = _WinHttpQueryHeaders($h_openRequest)
    ConsoleWrite($header & @CRLF & @CRLF)
    Global $chunk, $data, $extended
    While 1
        $chunk = X_WinHttpReadData($h_openRequest, 2)
        If Not @extended Then ExitLoop
        $data = _WinHttpBinaryConcat($data, $chunk)     
    WEnd
    ConsoleWrite(BinaryToString($data, 4) & @CRLF)
Else
    MsgBox(48, "Error", "Site is experiencing problems.")
EndIf

_WinHttpCloseHandle($h_openRequest)
_WinHttpCloseHandle($hw_connect)
_WinHttpCloseHandle($hw_open)


; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpReadData
; Description ...: Reads data from a handle opened by the _WinHttpOpenRequest() function.
; Syntax.........: _WinHttpReadData($hRequest [, iMode [, $iNumberOfBytesToRead]])
; Parameters ....: $hRequest - Valid handle returned from a previous call to _WinHttpOpenRequest().
;                  $iMode - Integer representing reading mode. Default is 0 (charset is taken to be ANSI related).
;                  $iNumberOfBytesToRead - Integer value that contains the number of bytes to read. Default is 8192 bytes.
; Return values .: Success - Returns data read.
;                          - Sets @error to 0
;                  Failure - Returns empty string and sets @error:
;                  |1 - DllCall failed.
; Author ........: trancexx, ProgAndy
; Modified.......:
; Remarks .......: iMode can have these values:
;                  |0 - ANSI 
;                  |1 - UTF8
;                  |2 - Binary
; Related .......:
; Link ..........; http://msdn.microsoft.com/en-us/library/aa384104(VS.85).aspx
; Example .......; Yes
;
;==========================================================================================
Func X_WinHttpReadData($hRequest, $iMode = 0, $iNumberOfBytesToRead = 8192) 

    Local $lpBuffer
    
    Switch $iMode
        Case 0
            $lpBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]")
        Case 1, 2
            $lpBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]")
    EndSwitch
    
    Local $a_iCall = DllCall("Winhttp.dll", "int", "WinHttpReadData", _
            "hwnd", $hRequest, _
            "ptr", DllStructGetPtr($lpBuffer), _
            "ulong", $iNumberOfBytesToRead, _
            "dword*", 0)

    If @error Or Not $a_iCall[0] Then
        SetError(1, 0, "")
    EndIf

    Switch $iMode
        Case 0
            Return SetError(0, $a_iCall[4], StringLeft(DllStructGetData($lpBuffer, 1), $a_iCall[4]))
        Case 1
            Return SetError(0, $a_iCall[4], BinaryToString(BinaryMid(DllStructGetData($lpBuffer, 1), 1, $a_iCall[4]), 4))
        Case 2
            Return SetError(0, $a_iCall[4], BinaryMid(DllStructGetData($lpBuffer, 1), 1, $a_iCall[4]))
    EndSwitch

EndFunc   

; #FUNCTION# ;===============================================================================
;
; Name...........: _WinHttpBinaryConcat
; Description ...: Concatenates two binary data returned by _WinHttpReadData() in binary mode.
; Syntax.........: _WinHttpBinaryConcat(ByRef $bBinary1, ByRef $bBinary2)
; Parameters ....: $bBinary1 - Binary data that is to be concatenated.
;                  $bBinary2 - Binary data to concat.
; Return values .: Success - Returns concatenated binary data.
;                          - Sets @error to 0
;                  Failure - Returns 0 and sets @error:
;                  |1 - Invalid input.
; Author ........: ProgAndy
; Modified.......: trancexx
; Remarks .......: 
; Related .......:
; Link ..........;
; Example .......; Yes
;
;==========================================================================================
Func _WinHttpBinaryConcat(ByRef $bBinary1, ByRef $bBinary2)
        
    Switch IsBinary($bBinary1) & IsBinary($bBinary2)
        Case 0
            Return SetError(1, 0, 0)
        Case 1
            Return SetError(0, 0, $bBinary2)
        Case 10
            Return SetError(0, 0, $bBinary1)
    EndSwitch           
    
    Local $iLen1 = BinaryLen($bBinary1)
    Local $iLen2 = BinaryLen($bBinary2)
    
    Local $struct = DllStructCreate("byte[" & $iLen1 & "];byte[" & $iLen2 & "]")
    DllStructSetData($struct, 1, $bBinary1)
    DllStructSetData($struct, 2, $bBinary2)
    
    Return DllStructGetData(DllStructCreate("byte[" & $iLen1 + $iLen2 & "]", DllStructGetPtr($struct)), 1)
    
EndFunc   ;==>_WinHttpBinaryConcatoÝ÷ Ù8Z¶+(¥éâaÊh²ÈX­É«­¢+Ø¥¹±ÕÅÕ½Ðí]¥¹!QQ@¹ÔÌÅÕ½Ðì(()±½°ÀÌØí¡Ý}½Á¸ô}]¥¹!ÑÑÁ=Á¸ ¤)%ÉɽÈQ¡¸(%5Í  ½à Ðà°ÅÕ½ÐíÉɽÈÅÕ½Ðì°ÅÕ½ÐíÉɽȥ¹¥Ñ¥±¥é¥¹Ñ¡Õͽ]¥¹!QQ@չѥ½¹Ì¸ÅÕ½Ðì¤(%á¥Ð)¹%()±½°ÀÌØí¡Ý}½¹¹Ðô}]¥¹!ÑÑÁ
½¹¹Ð ÀÌØí¡Ý}½Á¸°ÅÕ½ÐíÝÝܹÕѽ¥Ð¹ÅÕ½Ðì¤)%ÉɽÈQ¡¸(%5Í    ½à Ðà°ÅÕ½ÐíÉɽÈÅÕ½Ðì°ÅÕ½ÐíÉɽÈÍÁ¥å¥¹Ñ¡¥¹¥Ñ¥°ÑÉÐÍÉÙȽ¸!QQ@ÉÅÕÍиÅÕ½Ðì¤(%}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½Á¸¤(%á¥Ð)¹%()±½°ÀÌØí¡}½Á¹IÅÕÍÐô}]¥¹!ÑÑÁ=Á¹IÅÕÍÐ ÀÌØí¡Ý}½¹¹Ð¤)%ÉɽÈQ¡¸(%5Í    ½à Ðà°ÅÕ½ÐíÉɽÈÅÕ½Ðì°ÅÕ½ÐíÉɽÈÉÑ¥¹¸!QQ@ÉÅÕÍС¹±¸ÅÕ½Ðì¤(%}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½¹¹Ð¤(%}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½Á¸¤(%á¥Ð)¹%()}]¥¹!ÑÑÁM¹IÅÕÍÐ ÀÌØí¡}½Á¹IÅÕÍФ)%ÉɽÈQ¡¸(%5Í   ½à Ðà°ÅÕ½ÐíÉɽÈÅÕ½Ðì°ÅÕ½ÐíÉɽÈ͹¥¹Ñ¡ÍÁ¥¥ÉÅÕÍиÅÕ½Ðì¤(%}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½¹¹Ð¤(%}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½Á¸¤(%á¥Ð)¹%()}]¥¹!ÑÑÁI¥ÙIÍÁ½¹Í ÀÌØí¡}½Á¹IÅÕÍФ()%}]¥¹!ÑÑÁEÕÉåÑÙ¥±± ÀÌØí¡}½Á¹IÅÕÍФQ¡¸(%±½°ÀÌØí¡Èô}]¥¹!ÑÑÁEÕÉå!ÉÌ ÀÌØí¡}½Á¹IÅÕÍФ(%
½¹Í½±]É¥Ñ ÀÌØí¡ÈµÀì
I1µÀì
I1¤(%±½°ÀÌØí¡Õ¹¬°ÀÌØíÑ°ÀÌØíáѹ(%]¡¥±Ä($$ÀÌØí¡Õ¹¬ôa}]¥¹!ÑÑÁIÑ ÀÌØí¡}½Á¹IÅÕÍаĤ($%%9½ÐáѹQ¡¸á¥Ñ1½½À($$ÀÌØíѵÀìôÀÌØí¡Õ¹¬$(%]¹(%
½¹Í½±]É¥Ñ ÀÌØíѵÀì
I1¤)±Í(%5Í  ½à Ðà°ÅÕ½ÐíÉɽÈÅÕ½Ðì°ÅÕ½ÐíM¥Ñ¥ÌáÁÉ¥¹¥¹Áɽ±µÌ¸ÅÕ½Ðì¤)¹%()}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡}½Á¹IÅÕÍФ)}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½¹¹Ð¤)}]¥¹!ÑÑÁ
±½Í!¹± ÀÌØí¡Ý}½Á¸¤(((ìU9
Q%=8ìôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôô(ì(ì9µ¸¸¸¸¸¸¸¸¸¸¸è}]¥¹!ÑÑÁIÑ(ìÍÉ¥ÁÑ¥½¸¸¸¸èIÌÑɽ´¡¹±½Á¹äÑ¡}]¥¹!ÑÑÁ=Á¹IÅÕÍÐ ¤Õ¹Ñ¥½¸¸(ìMå¹Ñุ¸¸¸¸¸¸¸è}]¥¹!ÑÑÁIÑ ÀÌØí¡IÅÕÍÐl°¥5½l°ÀÌØí¥9ÕµÉ=  åÑÍQ½Iut¤(ìAɵÑÉ̸¸¸¸èÀÌØí¡IÅÕÍдY±¥¡¹±ÉÑÕɹɽ´ÁÉÙ¥½Õ̱°Ñ¼}]¥¹!ÑÑÁ=Á¹IÅÕÍÐ ¤¸(ìÀÌØí¥5½´%¹ÑÈÉÁÉ͹ѥ¹É¥¹µ½¸Õ±Ð¥ÌÀ¡¡ÉÍÐ¥ÌÑ­¸Ñ¼9M$ɱѤ¸(ìÀÌØí¥9ÕµÉ= åÑÍQ½I´%¹ÑÈÙ±Õѡн¹Ñ¥¹ÌÑ¡¹ÕµÈ½åÑÌѼɸձХÌàÄäÈåÑ̸(ìIÑÕɸٱÕ̸èMÕÍÌ´IÑÕɹÌÑɸ(ì´MÑÌÉɽÈѼÀ(쥱ÕÉ´IÑÕɹ̵ÁÑäÍÑÉ¥¹¹ÍÑÌÉɽÈè(ìðÄ´±±
±°¥±¸(ìÕÑ¡½È¸¸¸¸¸¸¸¸èÑɹáà°Aɽ¹ä(ì5½¥¥¸¸¸¸¸¸¸è(ìIµÉ­Ì¸¸¸¸¸¸¸è¥5½¸¡ÙÑ¡ÍÙ±ÕÌè(ìðÀ´9M$(ìðÄ´UQà(ìðÈ´   ¥¹Éä(ìI±Ñ¸¸¸¸¸¸¸è(ì1¥¹¬¸¸¸¸¸¸¸¸¸¸ì¡ÑÑÀè¼½µÍ¸¹µ¥É½Í½Ð¹½´½¸µÕ̽±¥ÉÉä½ÌàÐÄÀСYL¸àÔ¤¹ÍÁà(ìáµÁ±¸¸¸¸¸¸¸ìeÌ(ì(ìôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôôô)Õ¹a}]¥¹!ÑÑÁIÑ ÀÌØí¡IÅÕÍаÀÌØí¥5½ôÀ°ÀÌØí¥9ÕµÉ= åÑÍQ½IôàÄäȤ((%1½°ÀÌØí±Á  ÕÈ($(%MÝ¥Ñ ÀÌØí¥5½($%
ÍÀ($$$ÀÌØí±Á    ÕÈô±±MÑÉÕÑ
ÉÑ ÅÕ½Ðí¡ÉlÅÕ½ÐìµÀìÀÌØí¥9ÕµÉ=  åÑÍQ½IµÀìÅÕ½ÐítÅÕ½Ðì¤($%
ÍÄ°È($$$ÀÌØí±Á    ÕÈô±±MÑÉÕÑ
ÉÑ ÅÕ½ÐíåÑlÅÕ½ÐìµÀìÀÌØí¥9ÕµÉ=  åÑÍQ½IµÀìÅÕ½ÐítÅÕ½Ðì¤(%¹MÝ¥Ñ ($(%1½°ÀÌØí}¥
±°ô±±
±° ÅÕ½Ðí]¥¹¡ÑÑÀ¹±°ÅÕ½Ðì°ÅÕ½Ðí¥¹ÐÅÕ½Ðì°ÅÕ½Ðí]¥¹!ÑÑÁIÑÅÕ½Ðì°|($$$ÅÕ½Ðí¡Ý¹ÅÕ½Ðì°ÀÌØí¡IÅÕÍа|($$$ÅÕ½ÐíÁÑÈÅÕ½Ðì°±±MÑÉÕÑÑAÑÈ ÀÌØí±Á ÕȤ°|($$$ÅÕ½ÐíÕ±½¹ÅÕ½Ðì°ÀÌØí¥9ÕµÉ=   åÑÍQ½I°|($$$ÅÕ½ÐíݽɨÅÕ½Ðì°À¤((%%ÉɽÈ=È9½ÐÀÌØí}¥
±±lÁtQ¡¸($%MÑÉÉ½È Ä°À°ÅÕ½ÐìÅÕ½Ðì¤(%¹%((%MÝ¥Ñ ÀÌØí¥5½($%
ÍÀ($$%IÑÕɸMÑÉÉ½È À°ÀÌØí}¥
±±lÑt°MÑÉ¥¹1С±±MÑÉÕÑÑÑ ÀÌØí±Á  ÕȰĤ°ÀÌØí}¥
±±lÑt¤¤($%
ÍÄ($$%IÑÕɸMÑÉÉ½È À°ÀÌØí}¥
±±lÑt°  ¥¹ÉåQ½MÑÉ¥¹¡  ¥¹Éå5¥¡±±MÑÉÕÑÑÑ ÀÌØí±Á ÕȰĤ°Ä°ÀÌØí}¥
±±lÑt¤°Ð¤¤($%
ÍÈ($$%IÑÕɸMÑÉÉ½È À°ÀÌØí}¥
±±lÑt°  ¥¹Éå5¥¡±±MÑÉÕÑÑÑ ÀÌØí±Á ÕȰĤ°Ä°ÀÌØí}¥
±±lÑt¤¤(%¹MÝ¥Ñ ()¹Õ¹

Prefix "X" is used not to colide with current _WinHttpReadData() function

Find flaw, if any.

Maybe to set UTF-8 as default?

♡♡♡

.

eMyvnE

Posted (edited)

Good idea :mellow: But it would be faster, if it doesn't use BinaryMid/StringLeft when it is not needed:

...
    Select
        Case @error Or Not $a_iCall[0]
            Return SetError(1)
        Case Not $a_iCall[4]
            Return SetError(0)
        Case $a_iCall[4] < $iNumberOfBytesToRead
            Switch $iMode
                Case 0
                    Return SetError(0, $a_iCall[4], StringLeft(DllStructGetData($lpBuffer, 1), $a_iCall[4]))
                Case 1
                    Return SetError(0, $a_iCall[4], BinaryToString(BinaryMid(DllStructGetData($lpBuffer, 1), 1, $a_iCall[4]), 4))
                Case 2
                    Return SetError(0, $a_iCall[4], BinaryMid(DllStructGetData($lpBuffer, 1), 1, $a_iCall[4]))
            EndSwitch
    EndSelect
   
            Switch $iMode
                Case 0,2
                    Return SetError(0, $a_iCall[4], DllStructGetData($lpBuffer, 1), $a_iCall[4])
                Case 1
                    Return SetError(0, $a_iCall[4], BinaryToString(DllStructGetData($lpBuffer, 1), 4))
            EndSwitch
Edited by ProgAndy

*GERMAN* [note: you are not allowed to remove author / modified info from my UDFs]My UDFs:[_SetImageBinaryToCtrl] [_TaskDialog] [AutoItObject] [Animated GIF (GDI+)] [ClipPut for Image] [FreeImage] [GDI32 UDFs] [GDIPlus Progressbar] [Hotkey-Selector] [Multiline Inputbox] [MySQL without ODBC] [RichEdit UDFs] [SpeechAPI Example] [WinHTTP]UDFs included in AutoIt: FTP_Ex (as FTPEx), _WinAPI_SetLayeredWindowAttributes

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...