Jump to content

WinHTTP functions


trancexx
 Share

Recommended Posts

  • 2 weeks later...
On 3/5/2016 at 9:03 PM, trancexx said:

First thing, the UDFs inside the zip you posted don't have defined functions you use.
Second thing is why in the world you'd leave unused code inside a reproducer? What FileOpen, FileRead?!?
Third thing is I don't understand why do you constantly choose to make yourself life harder? Use _WinhttpSimpleFormFill(), and ditch JSON construction shit.

Try this ( just set correct access token):

#include "WinHttp.au3"

$sAccessToken = "a.2g3Ymc00aAGgibbbbQDvqnX7u5p3TG34" ; write yours here
$sIden = ""; to whatever device you want

$hOpen = _WinHttpOpen()

; PUSH!!!!!
$sAddress = "https://api.pushbullet.com/v2/pushes"
$sForm = _
        '<form action="' & $sAddress & '" method="post" enctype="multipart/form-data">' & _
        ' <input name="device_iden" />' & _
        ' <input name="type" />' & _
        ' <input name="file_name" />' & _
        ' <input name="file_type" />' & _
        ' <input name="file_url" />' & _
        ' <input name="body" />' & _
        '</form>'

$hConnect = $sForm
$sReturnedThing = _WinHttpSimpleFormFill($hConnect, $hOpen, _
        Default, _
        "name:device_iden", $sIden, _
        "name:type", "file", _
        "name:file_name", "picard-wtf.jpg", _
        "name:file_type", "image/jpg", _
        "name:file_url", "http://evolutionaryparenting.com/wp-content/uploads/2015/01/picard-wtf.jpg", _
        "name:body", "Hey!", _
        'Authorization: Bearer ' & $sAccessToken)

MsgBox(4096, "Returned", $sReturnedThing & @CRLF & "@error = " & @error & @CRLF & "@extended = " & @extended)
; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

 

Hey

with this i can send files that are in the www how can i send files thats on my hdd??

 

can u help me?

Link to comment
Share on other sites

 

I am having issues sending a JSON string using winhttp if anyone can help me, thanks. The initial HTTP error I was getting is 400, error Bad Request. 

It should be array of destination objects",txid":"f5b74"}

 After formatting $sDta like below 

Global $sDta = '{'  & _
    '\"destination \":\"testadd99.com \", '  & _
    '\"comment \":\"Comment99 \", '  & _
    '}'

 I now get  

Response: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: No default engine was specified and no extension was provided.<br> &nbsp; &nbsp;at new View (/usr/src/app/node_modules/express/lib/view.js:61:11)<br> &nbsp; &nbsp;at Function.render (/usr/src/app/node_modules/express/lib/application.js:570:12)<br> &nbsp; &nbsp;at ServerResponse.render (/usr/src/app/node_modules/express/lib/response.js:1008:7)<br> &nbsp; &nbsp;at /usr/src/app/dist/utils/securityheaders.js:41:13<br> &nbsp; &nbsp;at Layer.handle_error (/usr/src/app/node_modules/express/lib/router/layer.js:71:5)<br> &nbsp; &nbsp;at trim_prefix (/usr/src/app/node_modules/express/lib/router/index.js:315:13)<br> &nbsp; &nbsp;at /usr/src/app/node_modules/express/lib/router/index.js:284:7<br> &nbsp; &nbsp;at Function.process_params (/usr/src/app/node_modules/express/lib/router/index.js:335:12)<br> &nbsp; &nbsp;at next (/usr/src/app/node_modules/express/lib/router/index.js:275:10)<br> &nbsp; &nbsp;at Layer.handle_error (/usr/src/app/node_modules/express/lib/router/layer.js:67:12)</pre>
</body>
</html>

Here is the code I am using.

#include <WinHttp.au3>

Global $Domain = "https://management.api.umbrella.com/"

Global $sTarget = "v1/organizations/12345/destinationlists/54321/destinations"

Global $sHeader = _
            'Authorization: Basic XYZ' & @CRLF & _
            'Accept: application/json' & @CRLF & _
            'Content-Type: application/json'

Global $sDta = '{'  & _
    '\"destination \":\"testadd99.com \", '  & _
    '\"comment \":\"Comment99 \", '  & _
    '}'

Global $hOpen = _winhttpOpen()
If @error Then
    Exit 1
EndIf

Global $hConnect = _winhttpConnect($hOpen, $Domain)
If @error Then
    _WinHttpCloseHandle($hOpen)
    Exit 2
EndIf

Global $hRequest = _WinHttpSimpleSSLRequest($hConnect,"POST", $sTarget, Default, $sDta, $sHeader, Default, Default, Default, Default, 1)

ConsoleWrite("Response: "& $hRequest & @CRLF)

If @error Then
    _WinHttpCloseHandle($hConnect)
    _WinHttpCloseHandle($hOpen)
    Exit 3
EndIf

;Send the request
_WinHttpSendRequest($hRequest)

API documentation, https://docs.umbrella.com/umbrella-api/reference#post_v1-organizations-organizationid-destinationlists-destinationlistid-destinations

image.png

Link to comment
Share on other sites

ok, I found that this one line string works

Global $sDta = '[{"destination":"testing99.com","comment":"COMMENT99"}]'

Now I need to figure out how to replcae tesing99.com and COMMENT99 with $varibles.

Fixed it, posting answer as it may help somone else.

$URL = "testing1003.com"
$Comment = "Comment1003"

Global $sDta = '[{"destination":"' & $URL & _
               '","comment":"' & $Comment & _
               '"}]'

 

Edited by Remo_
Link to comment
Share on other sites

Tried that, :). Here is the UDF, under $Type, I am only seeing GET or POST, no DELETE.

 

; #FUNCTION# ====================================================================================================================
; Name...........: _WinHttpSimpleSSLRequest
; Description ...: A function to send a SSL request in a simpler form
; Syntax.........: _WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default ]]]]]]])
; Parameters ....: $hConnect  - Handle from _WinHttpConnect
;                  $sType       - [optional] GET or POST (default: GET)
;                  $sPath       - [optional] request path (default: "" - empty string; meaning 'default' page on the server)
;                  $sReferrer   - [optional] referrer (default: $WINHTTP_NO_REFERER)
;                  $sDta        - [optional] POST-Data (default: $WINHTTP_NO_REQUEST_DATA)
;                  $sHeader     - [optional] additional Headers (default: $WINHTTP_NO_ADDITIONAL_HEADERS)
;                  $fGetHeaders - [optional] return response headers (default: False)
;                  $iMode       - [optional] reading mode of result
;                  |0 - ASCII-text
;                  |1 - UTF-8 text
;                  |2 - binary data

image.png.e87279ffeb3d4d98ed72a2f10bef7843.png

 

Edited by Remo_
Link to comment
Share on other sites

  • 2 weeks later...
  • 3 weeks later...

Hey @trancexx, first of all thank you and @ProgAndy for this great UDF!

But isn't "_WinHttpSimpleSSLRequest" function description in the help file incomplete? It reads:

_WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default ]]]]]]])

Shouldn't it be:

_WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default [, $sCredName = Default [, $sCredPass = Default [, $iIgnoreCertErrors = 0 ]]]]]]]]]]])

Here is an example if you want to include it inside the help file as well:

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

Opt("MustDeclareVars", 1)

; My server
Global $sLocalIP = "127.0.0.1"
Global $sPort = "58458"
Global $sUrl = "/url/to/requested/page/"
Global $sLogin = "admin"
Global $sPassword = "adminpassword"
; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sLocalIP, $sPort)
; Specify the reguest
Global $hRequest = _WinHttpSimpleSSLRequest($hConnect,"GET", $sUrl, Default, Default, Default, True , Default, $sLogin, $sPassword, 1)

if IsArray($hRequest) then _arraydisplay($hRequest)

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

It might also be good to add in the "_WinHttpSetCredentials" function help file that for https credentials should be set using _WinHttpSimpleSendSSLRequest if that's the case.

Thanks :)

 

Edited by Neutro
Link to comment
Share on other sites

8 hours ago, Neutro said:

Hey @trancexx, first of all thank you and @ProgAndy for this great UDF!

But isn't "_WinHttpSimpleSSLRequest" function description in the help file incomplete? It reads:

_WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default ]]]]]]])

Shouldn't it be:

_WinHttpSimpleSSLRequest($hConnect [, $sType [, $sPath [, $sReferrer = Default [, $sDta = Default [, $sHeader = Default [, $fGetHeaders = Default [, $iMode = Default [, $sCredName = Default [, $sCredPass = Default [, $iIgnoreCertErrors = 0 ]]]]]]]]]]])

Here is an example if you want to include it inside the help file as well:

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

Opt("MustDeclareVars", 1)

; My server
Global $sLocalIP = "127.0.0.1"
Global $sPort = "58458"
Global $sUrl = "/url/to/requested/page/"
Global $sLogin = "admin"
Global $sPassword = "adminpassword"
; Initialize and get session handle
Global $hOpen = _WinHttpOpen()
; Get connection handle
Global $hConnect = _WinHttpConnect($hOpen, $sLocalIP, $sPort)
; Specify the reguest
Global $hRequest = _WinHttpSimpleSSLRequest($hConnect,"GET", $sUrl, Default, Default, Default, True , Default, $sLogin, $sPassword, 1)

if IsArray($hRequest) then _arraydisplay($hRequest)

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

It might also be good to add in the "_WinHttpSetCredentials" function help file that for https credentials should be set using _WinHttpSimpleSendSSLRequest if that's the case.

Thanks :)

I prefer leaving last three parameters undocumented for forward compatibility reasons. They're used internally.

Link to comment
Share on other sites

Thanks for your answer :)

So this means that _WinHttpSetCredentials should be used even with https?

I've tried using it alongside _WinHttpSimpleSSLRequest with no credentials parameters but never could make it work :(

 

Link to comment
Share on other sites

  • 1 month later...

 

Hi, I'm trying to understand if I can use WinHttp to make my idea but I have some problems starting from the basics :

I tried the script of the initial example ( also tried with "google.com" + "GET" ), reading the post I found an example posted by another user declared functional, I also tried the one  and  after try the example for <_WinHttpQueryDataAvailable>  I get the error message set in the sript  <<Site is experiencing problems (or you).>> 

I found out that I was being blocked by the farewall (so I enabled the operation) and things got a little better.

 

 

but I still have some doubts, for example if I try with "google.com" + "GET","google.com"  as a result I get something like this:

<!DOCTYPE html>


<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>404.</b> <ins>That’s an error.</ins>
  <p>The requested URL <code>/google.com</code> was not found on this server.  <ins>That’s all we know.</ins>

a) is this right ?  is there any setting that does not make those work (websites aside) ?  

b) if I didn't get it wrong the reference link must point to a page but if the address is for example an image or an image container it doesn't work or is there any option that I couldn't find ? 

for example I had to use: 

h**ps://www.lastampa.it/image/contentid/policy:1.38524329:1582812892/puppy-looks-like-cat-dog-hybrid-14-5e53858271f0f__700.jpg

or  h**ps://s://mangadex.org/chapter/832015/6

 

is there any way to result in the height and width values that can be found via the browser's inspect command ?

 

[at the beginning I thought to point to the tag "img" but if the link is directed to an image the script does not work I fear ... is this so or is there a way ? ]

 

 

 

 

Link to comment
Share on other sites

  • 1 month later...
  • 2 weeks later...

Hi @trancexx, I'm trying to upload a file to a site without success. Here is the PHP file I'm using:

<!DOCTYPE html>
<title>Upload your files</title>
<body>
    <form enctype="multipart/form-data" action="upload.php" method="post">
      <!--<p>Upload your file</p> -->
        <input type="file" name="fileToUpload">
        <input type="submit" value="Upload">
    </form>
</body>

<?PHP
// info for uploadslog.txt --------------------
$referer = $_SERVER['HTTP_REFERER'];
$host = $_SERVER['REMOTE_HOST'];
$port = $_SERVER['REMOTE_PORT'];

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$file_type = $_FILES['fileToUpload']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['fileToUpload']['name'])));
$file_tmp = $_FILES['fileToUpload']['tmp_name'];

$upload_status = $_FILES['fileToUpload']['error'];
$upload_dir = "uploads/";
$upload_file = $upload_dir . basename($_FILES["fileToUpload"]["name"]);

$errors = array();

/* if (file_exists($upload_file)) {
  // echo "File already exists.";
  $errors[] = " File already exists.";
  } */

/* $extensions = array("jpeg", "jpg", "png", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "txt");
  if (in_array($file_ext, $extensions) === false) {
  $errors[] = " Extension not allowed.";
  } */

/* if ($file_size > 5000000) { //5MB
  $errors[] = ' File size exeeds maximun allowed.';
  } */

if (!empty($_FILES['fileToUpload'])) {

    $fp = fopen('uploadslog.txt', 'a');

    if (empty($errors)) {

        $upload_status = " File not uploaded.";

        if (move_uploaded_file($file_tmp, $upload_file)) {
//      echo "The file ".  basename( $_FILES['uploaded_file']['name'])." has been uploaded";
            switch ($_FILES['fileToUpload']['error']) {
                case 0:
                    $upload_status = " There is no error, the file uploaded with success.";
                    break;
                case 1:
                    $upload_status = " The uploaded file exceeds the upload_max_filesize directive in php.ini.";
                    break;
                case 2:
                    $upload_status = " The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
                    break;
                case 3:
                    $upload_status = " The uploaded file was only partially uploaded.";
                    break;
                case 4:
                    $upload_status = " No file was uploaded.";
                    break;
                case 6:
                    $upload_status = " Missing a temporary folder. Introduced in PHP 5.0.3.";
                    break;
                case 7:
                    $upload_status = " Failed to write file to disk. Introduced in PHP 5.1.0.";
                    break;
                case 8:
                    $upload_status = " A PHP extension stopped the file upload. ; examining the list of loaded extensions with phpinfo() may help.";
                    break;
                default:
                    $upload_status = " Undetermined upload status.";
            }
            fwrite($fp, 'IP:' . $ip . '  Port: ' . $port . '  Timestamp:' . date("d/m/Y") . "-" . date("h:i:sa") . '  Website:' . $referer . ' Host:' . $host .
                    ' File name:' . $file_name . ' File size: ' . $file_size . ' File type: ' . $file_type .
                    ' File status:' . $upload_status . "\r\n");
        } else {
//   echo "There was an error uploading the file, please try again!";

            fwrite($fp, 'IP:' . $ip . '  Port: ' . $port . '  Timestamp:' . date("d/m/Y") . "-" . date("h:i:sa") . '  Website:' . $referer . ' Host:' . $host .
                    ' File name:' . $file_name . ' File size: ' . $file_size . ' File type: ' . $file_type . 'Error to upload: ' . $errors .
                    ' File status:' . $upload_status . "\r\n");
        }
    } else {
        /* echo " File extension or file size not allowed, or file already exists!"; */
        fwrite($fp, 'IP:' . $ip . '  Port: ' . $port . '  Timestamp:' . date("d/m/Y") . "-" . date("h:i:sa") . '  Website:' . $referer . ' Host:' . $host .
                ' File name:' . $file_name . ' File size: ' . $file_size . ' File type: ' . $file_type . ' Error to upload: ' . $errors . ' File status:' . $upload_status . "\r\n");
    }
    fclose($fp);
}
?>

and this is the script:

#include "WinHttp.au3"
Opt("MustDeclareVars", 1)

Global $hOpen, $hConnect, $sRead
Global $file = @ScriptDir & "\hi.txt"

$hOpen = _WinHttpOpen()
$hConnect = _WinHttpConnect($hOpen, "jcpetu.0fees.us")

$sRead = _WinHttpSimpleFormFill($hConnect, "/upload.php", "index:0", "name:fileToUpload", $file)

_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

The script doesn't fail at all but the file is not uploaded.

Any help will be appreciated. Thanks in advance.

 

Link to comment
Share on other sites

  • 4 weeks later...
On 11/9/2008 at 5:28 PM, trancexx said:

The other day mikeytown2 posted one post in HTTP UDF's thread that got me thinking if there is better (different) method to send requests through the HTTP protocol to HTTP servers.

There is Winhttp.dll that ships with windows and that is its main purpose. I couldn't find any examples of using this dll in AutoIt, so I came up with this.

Microsoft about Windows HTTP Services:
Microsoft Windows HTTP Services (WinHTTP) provides developers with an HTTP client application programming interface (API) to send requests through the HTTP protocol to other HTTP servers...
.. blah, blah, and so on...


This is an example of getting page header:

#include "WinHttp.au3"

Opt("MustDeclareVars", 1)

; Open needed handles
Local $hOpen = _WinHttpOpen()
Local $hConnect = _WinHttpConnect($hOpen, "msdn.microsoft.com")
; Specify the reguest:
Local $hRequest = _WinHttpOpenRequest($hConnect, Default, "en-us/library/aa384101(VS.85).aspx")

; Send request
_WinHttpSendRequest($hRequest)

; Wait for the response
_WinHttpReceiveResponse($hRequest)

Local $sHeader = _WinHttpQueryHeaders($hRequest) ; ...get full header

; Clean
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

; Display retrieved header
MsgBox(0, "Header", $sHeader)

Everything you need to be able to use this UDF can be found at WinHttp site.



Remember, basic understanding of the HTTP protocol is important to use this interface.


 

ProgAndy, trancexx

 

 

 

 

WinHttp.au3 is completely free and no one has right to charge you for it. That's very important.
If you feel WinHttp.au3 was helpful to you and you wish to support my further work you can donate to my personal account via PayPal address: trancexx at yahoo dot com
I will appreciate that very much. Thank you in advance! 💋

 

Hi,

Where to download WinHttp.au3 ?

Link to comment
Share on other sites

1 minute ago, AutoFan said:

Everything you need to be able to use this UDF can be found at WinHttp site.

Does the link not work for you?

Link to comment
Share on other sites

  • 1 month later...

Hello, I've been trying to work with the slack API to upload files for a while now. I've tried the builtin winhttprequest5.1, curl.au3, and a few others. I think I have came the closes using the below code with WinHttp.au3, but still not quite there. The slack API that I'm trying to use: https://api.slack.com/methods/files.upload and an example curl command is in the code.

When I run the code below I get:

Response: {"ok":false,"error":"invalid_arg_name"}

 

When I leave out the '&file=' I get:

Response: {"ok":false,"error":"no_file_data"}

So I think it is authenticating, I just need get the argument for the file and how to upload the file. 

Any help would be greatly appreciated!

 

Code:

#include <WinHttp.au3>

$url = "https://slack.com/api/files.upload"
$token = "abc-123-456-abc123"
$args = "channels=#random"
$file = "c:\Users\Public\catloloz.jpg"

; example curl command -- curl -F file=@c:\Users\Public\catloloz.jpg -F channels=#random -F token=abc-123-456-abc123 https://slack.com/api/files.upload

Global $Domain = "https://slack.com/"
Global $sTarget = "api/files.upload"
Global $sHeader = 'Content-Type: application/x-www-form-urlencoded'
Global $bFile = FileRead($file)
Global $sDta = 'channel=#random&token=' & $token & '&file=' & $bFile

Global $hOpen = _winhttpOpen()
If @error Then
    Exit 1
EndIf

Global $hConnect = _winhttpConnect($hOpen, $Domain)
If @error Then
    _WinHttpCloseHandle($hOpen)
    Exit 2
EndIf

Global $hRequest = _WinHttpSimpleSSLRequest($hConnect,"POST", $sTarget, Default, $sDta, $sHeader, Default, Default, Default, Default, 1)

ConsoleWrite("Response: "& $hRequest & @CRLF)

If @error Then
    _WinHttpCloseHandle($hConnect)
    _WinHttpCloseHandle($hOpen)
    Exit 3
EndIf

;Send the request
_WinHttpSendRequest($hRequest)
Link to comment
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
 Share

  • Recently Browsing   0 members

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