[How To] Do logins using the WinHttpRequest COM

Helpful script writing tricks and HowTo's
Bruttosozialprodukt
Posts: 463
Joined: 24 Jan 2014, 22:28

[How To] Do logins using the WinHttpRequest COM

Post by Bruttosozialprodukt » 22 Jul 2014, 08:09

I just realized that the WinHttpRequest object has built in cookie handling. And since so many people had trouble doing logins using the WinHttpRequest COM and we always thought that this would be because of the cookies, I'm now giving you two working, very well explained login examples, as well as some tips on how to get started reverseengineering HTML / HTTP-Requests.

If you want to do complicated things like logins, then you should really learn some HTML and the basics about the HTTP protocol. Fiddler and SetProxy(2,"localhost:8888") will help you A LOT with the debugging. I also recommend using an add on for your browser to quickly clean your cookies.

To reverse engineer the AHK forum login I simply analyzed the browsers HTTP requests to autohotkey.com and by some trial and error I was able to minimize it to the basics. We need exactly two requests and the login needs one request headers and 3 POST data parameters.

So let's do this login to the AHK forums. (Note: the first example is about the forum on autohotkey.com)
Step 1. Do a simple GET request on http://www.autohotkey.com/board/index.p ... tion=login
Step 2. Extract the auth_key parameter form the login form from the response body (ResponseText)
Step 3. Create the POST data string containing the auth_key parameter as well as the username, password and rememberMe parameter for the login
Step 4. Set the Content-Type header for the next request
Step 5. Send the POST data string to http://www.autohotkey.com/board/index.p ... do=process
Step 6. Analyze the response body checking if the HTML documents title starts with the words "Sign In". If so, then you're obviously not signed in (the login failed/wrong login data). If the title is different, then the login was successfull.

Code: Select all

;Prepare our WinHttpRequest object
HttpObj := ComObjCreate("WinHttp.WinHttpRequest.5.1")
;HttpObj.SetProxy(2,"localhost:8888") ;Send data through Fiddler
HttpObj.SetTimeouts(6000,6000,6000,6000) ;Set timeouts to 6 seconds
;HttpObj.Option(6) := False ;disable location-header rediects

;Set our URLs
loginSiteURL := "http://www.autohotkey.com/board/index.php?app=core&module=global&section=login"
loginURL := "http://www.autohotkey.com/board/index.php?app=core&module=global&section=login&do=process"

;Set our login data
username := "Brutosozialprodukt"
password := "xxxxxxxxxxxxxx"
rememberMe := "1"

;Step 1
HttpObj.Open("GET",loginSiteURL)
HttpObj.Send()

;Step 2
RegExMatch(HttpObj.ResponseText,"<input\stype='hidden'\sname='auth_key'\svalue='(\w+)'\s/>",match)
auth_key := match1

;Step 3
loginBody := "auth_key=" auth_key "&ips_username=" username "&ips_password=" password "&rememberMe=" rememberMe

;Step 4/5
HttpObj.Open("POST",loginURL)
HttpObj.SetRequestHeader("Content-Type","application/x-www-form-urlencoded")
HttpObj.Send(loginBody)

;Step 6
If (InStr(HttpObj.ResponseText,"<title>Sign In"))
    MsgBox, The login failed!
Else
    MsgBox, Login was successfull!
This will probably work for most IPB forums if change the URLs properly. For other sites this will be probably look very different.

But okay, let's do another login to the new/other AHK forum (this will be much easier).
Step 1. Create the POST data containing username, password and the autologin parameter
Step 2. Set the Content-Type header
Step 3. Send the POST data to http://ahkscript.org/boards/ucp.php?mode=login
Step 4. Analyze the response body checking if the HTML documents title starts with the word "Login". If so, then you're obviously not logged in yet (the login failed/wrong login data). If the title is different, then the login was successfull.

Code: Select all

;Prepare our WinHttpRequest object
HttpObj := ComObjCreate("WinHttp.WinHttpRequest.5.1")
;HttpObj.SetProxy(2,"localhost:8888") ;Send data through Fiddler
HttpObj.SetTimeouts(6000,6000,6000,6000) ;Set timeouts to 6 seconds
;HttpObj.Option(6) := False ;disable location-header rediects

;Set our URLs
loginURL := "http://ahkscript.org/boards/ucp.php?mode=login"

;Set our login data
username := "Brutosozialprodukt"
password := "xxxxxxxxxxxxxx"
autologin := "on"

;Step 1
loginBody := "username=" username "&password=" password "&autologin=" autologin "&login=Login"

;Step 2/3
HttpObj.Open("POST",loginURL)
HttpObj.SetRequestHeader("Content-Type","application/x-www-form-urlencoded")
HttpObj.Send(loginBody)

;Step 4
If (InStr(HttpObj.ResponseText,"<title>Login"))
    MsgBox, The login failed!
Else
    MsgBox, Login was successfull!
Any questions? I will try to answer them the next time I'm here. :)
You may also read the existing answers in this thread or the one on the other forum.
Last edited by Bruttosozialprodukt on 24 Jul 2014, 17:05, edited 4 times in total.
User avatar
tank
Posts: 3164
Joined: 28 Sep 2013, 22:15
Location: CarrolltonTX
Contact:

Re: [How To] Do logins using the WinHttpRequest COM

Post by tank » 22 Jul 2014, 08:37

you know that once the auto login is set you should never need to log On again?
I understand the point of this thread is to help people understand how to create heep requests with no browser.
Content-Length isnt necesary it will be calculated automatically. For POST Content-Type IS required tho good job

If i see signs of abuse from logon scripts i may be forced to make changes that break this example without notice.

Finally i would like to offer encouragement. but there are many pitfalls to logon scripts because some sites require live data retreived by ajax call as part of submitted data. there is difficulty at times understanding what is being submitted and where. a took such as fiddler can help but there is a learning curve not to be ignored

now a challenge (hint: lexikos demonstrated this somewhere can you find it ?) use http://msdn.microsoft.com/en-us/library ... s.85).aspx
and demonstrate a binary file upload on a site like dropbox. and add it to this tutorial
We are troubled on every side‚ yet not distressed; we are perplexed‚
but not in despair; Persecuted‚ but not forsaken; cast down‚ but not destroyed;
Telegram is the best way to reach me
https://t.me/ttnnkkrr
If you have forum suggestions please submit a
Check Out WebWriter
Bruttosozialprodukt
Posts: 463
Joined: 24 Jan 2014, 22:28

Re: [How To] Do logins using the WinHttpRequest COM

Post by Bruttosozialprodukt » 22 Jul 2014, 10:43

tank wrote:you know that once the auto login is set you should never need to log On again?
But since a session is terminated anyway when the script closes, this shouldn't be a problem right?
The option could help if you put your computer into sleep or hibernate without closing the script, so the script would still run if you turn on the computer 2 days later.
tank wrote:Content-Length isnt necesary it will be calculated automatically.
Good point, haven't thought about that!
tank wrote:If i see signs of abuse from logon scripts i may be forced to make changes that break this example without notice.
Sure, it's your forum. ;) In fact I think that you should definitely change the login/sign up so that standard phpBB spam bots can't login anymore.
tank wrote:some sites require live data retreived by ajax call as part of submitted data. there is difficulty at times understanding what is being submitted and where. a took such as fiddler can help but there is a learning curve not to be ignored
For these kinds of logins it can help a lot to learn javascript. The ajax function of jquery is pretty much based on XmlHttpRequest which is extremely similar (if not the same) as WinHttpRequest.
In rare cases (in some flash games) the http requests are actually sent through the swf files without any javascript.
For these cases you could learn some ActionScript and decompile the swf with one of the many decompilers available or you have to reverseengineer it by looking at Fiddler's log.
tank wrote:now a challenge (hint: lexikos demonstrated this somewhere can you find it ?) use http://msdn.microsoft.com/en-us/library ... s.85).aspx
and demonstrate a binary file upload on a site like dropbox. and add it to this tutorial
I have actually done that before. But it's not possible using WinHttpRequest since the functions are expecting null-terminated strings.
I had to build a new HTTPRequest function from scratch involving a ton of complicated DLL-Calls.. But Lexikos helped me A LOT with this. But the function is still not finished... For example I definitely need to add an option to download/upload files in chunks so that there are no problems on low-RAM computers.

Code: Select all

HttpRequest(url,method:="",headers:="",ByRef body:="",proxy:="",pExcludeList:="",httpVersion:="",sessionOptions:="",requestOptions:="") {
    ;Makes working with the msdn functions easier
    static LPCWSTR:="UPTR"
    static DWORD:="UInt"
    static LPCVOID:="UPTR"
    static LPDWORD:="UPTR"
    static HINTERNET:="UPTR"
    static INTERNET_PORT:="UShort"
    static DWORD_PTR:="UPTR"
    static LPVOID:="UPTR"
    static NULL := 0
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Not supported so far
    asynch := False
    VarSetCapacity(callbackValue,A_PtrSize)
    ;;;;;;;;;;;;;;;;;;;;;
    
    ;Crack URL to use it's segments in the upcomming DllCalls
    VarSetCapacity(myStruct,60,0)
    numput(60,myStruct,0,"Uint") ; this dll function requires this to be set
    numput(1,myStruct,8,"Uint") ; SchemeLength
    numput(1,myStruct,20,"Uint") ; HostNameLength
    ;numput(1,myStruct,32,"Uint") ; UserNameLength
    ;numput(1,myStruct,40,"Uint") ; PasswordLength
    numput(1,myStruct,48,"Uint") ; UrlPathLength
    numput(1,myStruct,56,"Uint") ; ExtraInfoLength
    DllCall("Winhttp.dll\WinHttpCrackUrl","PTR",&url,"UInt",StrLen(url),"UInt",0,"PTR",&myStruct)
    
    scheme := StrGet(NumGet(myStruct,4,"Ptr"),NumGet(myStruct,8,"UInt"))
    ;userName := StrGet(NumGet(myStruct,28,"Ptr"),NumGet(myStruct,32,"UInt"))
    ;password := StrGet(NumGet(myStruct,36,"Ptr"),NumGet(myStruct,40,"UInt"))
    hostName := StrGet(NumGet(myStruct,16,"Ptr"),NumGet(myStruct,20,"UInt"))
    port := NumGet(myStruct,24,"Int")
    urlPath := StrGet(NumGet(myStruct,44,"Ptr"),NumGet(myStruct,48,"UInt"))
    extraInfo := StrGet(NumGet(myStruct,52,"Ptr"),NumGet(myStruct,56,"UInt"))
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Make the url parts usable
    If (scheme = "https") {
        port := (port) ? port : 443
        https := True
    } Else 
        https := False
    
    resource := urlPath . extraInfo
    ;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Parse headers and convert them to be usable
    addHeaders := ""
    acceptedTypes := []
    For header, value in headers 
    {
        If (header = "User-Agent")
            userAgent := value
        Else If (header = "Referer")
            referrer := value
        Else If (header = "Accept") {
            Loop, parse, acceptedTypes, `;
                acceptedTypes.Insert(value)
        } Else If (header = "Content-Length")
            bodySize := value
        Else
            addHeaders .= header . ": " . value . "`r`n"
    }
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Parse proxy exclude list and make it usable
    proxyBypassString := ""
    Loop, % pExcludeList.MaxIndex()
        proxyBypassString .= pExcludeList[A_Index] . ";"
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Initialize WinHttp application
    hSession := DllCall("Winhttp.dll\WinHttpOpen"
                       ,LPCWSTR,&userAgent
                       ,DWORD, (proxy) ? 3 : 1
                       ,LPCWSTR,&proxy
                       ,LPCWSTR,(pExcludeList) ? pExcludeList : NULL
                       ,DWORD,asynch)    
    If (!hSession)
        Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"WinHttp initialization failed"} ;Msgbox,, hSession, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Set session options
    For optionKey, optionValue in sessionOptions
    {
        oResult := DllCall("Winhttp.dll\WinHttpSetOption"
               ,HINTERNET,hConnect
               ,DWORD,optionKey
               ,LPVOID,&optionValue
               ,DWORD,StrLen(optionValue))
        If !(oResult)
            Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Setting session option #" . A_Index . " failed"}
    }
    ;;;;;;;;;;;;;;;;;;;;
    
    ;Specify target server
    hConnect := DllCall("Winhttp.dll\WinHttpConnect"
                       ,HINTERNET,hSession
                       ,LPCWSTR,&hostName
                       ,INTERNET_PORT,port
                       ,DWORD,0)    
    If (!hConnect)
        Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Creating connect handle failed"} ;Msgbox,, hConnect, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    ;;;;;;;;;;;;;;;;;;;;;;
    
    ;Create request handle
    hRequest := DllCall("Winhttp.dll\WinHttpOpenRequest"
                      ,HINTERNET,hConnect
                      ,LPCWSTR,(method) ? &method : NULL
                      ,LPCWSTR,(resource) ? &resource : NULL
                      ,LPCWSTR,(httpVersion) ? &httpVersion : NULL
                      ,LPCWSTR,(referrer) ? &referrer : NULL
                      ,LPCWSTR,(acceptedTypes.MaxIndex()) ? &acceptedTypes : NULL
                      ,DWORD,(https) ? 0x00800000 : NULL)
    If (!hRequest)
        Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Creating request handle failed"} ;Msgbox,, hRequest, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    ;;;;;;;;;;;;;;;;;;;;;;
    
    ;Set request options
    For optionKey, optionValue in requestOptions
    {
        oResult := DllCall("Winhttp.dll\WinHttpSetOption"
               ,HINTERNET,hConnect
               ,DWORD,optionKey
               ,LPVOID,&optionValue
               ,DWORD,StrLen(optionValue))
        If !(oResult)
            Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Setting request option #" . A_Index . " failed"}
    }
    ;;;;;;;;;;;;;;;;;;;;
    
    ;Send request to server
    bResults := DllCall("Winhttp.dll\WinHttpSendRequest"
                       ,HINTERNET,hRequest
                       ,LPCWSTR,&addHeaders
                       ,DWORD,StrLen(addHeaders)
                       ,LPVOID,&body
                       ,DWORD,(bodySize) ? bodySize : StrLen(body)*2
                       ,DWORD,(bodySize) ? bodySize : StrLen(body)*2
                       ,DWORD_PTR,&callbackValue)
    If (!bResults)
        Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Sending the request failed"} ; Msgbox,, bResults 1, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    ;;;;;;;;;;;;;;;;;;;;;;
    
    ;Receive server response
    bResults := DllCall("Winhttp.dll\WinHttpReceiveResponse"
                       ,HINTERNET,hRequest
                       ,LPVOID,NULL)        
    If (!bResults)
        Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Receiving server response failed"} ; Msgbox,, bResults 1, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    ;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Receive the response body
    responseBody := ""
    VarSetCapacity(dwDownloaded,8)
    Loop {
        dwSize := 0
        If (!DllCall("Winhttp.dll\WinHttpQueryDataAvailable"
                    ,HINTERNET,hRequest
                    ,LPDWORD,&dwSize)) {
            Return % {Body:"",Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Getting info about available response data failed"} ;Msgbox,, hRequest, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
        } Else
            dwSize := Asc(dwSize)
        
        If (!dwSize)
            Break
        
        VarSetCapacity(pszOutBuffer,Asc(dwSize)+1,0)
        If (!DllCall("Winhttp.dll\WinHttpReadData"
                    ,HINTERNET,hRequest
                    ,LPVOID,&pszOutBuffer
                    ,DWORD,dwSize
                    ,LPDWORD,&dwDownloaded)) {
            MsgBox % "error:" A_LastError
        } Else {
            Loop, % Asc(dwDownloaded)
                responseBody .= Chr(NumGet(&pszOutBuffer,A_Index-1,"UChar"))
        }
        
        If (!dwDownloaded)
            break
            
     If (dwSize <= 0)
      Break
    }
    ;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Receive response headers
    dwSize := 0
    bResults := DllCall("Winhttp.dll\WinHttpQueryHeaders"
           ,HINTERNET,hRequest
           ,DWORD,22 ;raw
           ,LPCWSTR, NULL
           ,LPVOID, NULL
           , "UIntP", dwSize
           ;,LPDWORD, &dwSize
           ,LPDWORD, NULL)

    If (!bResults && A_LastError != 122) ; allow function to proceed if it was a buffer size error
        Return % {Body:responseBody,Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Getting the size of the response headers failed"} 
    If (A_LastError = 122) { ;buffer too small
        ;lpOutBuffer := new WCHAR[dwSize/sizeof(WCHAR)]

        VarSetCapacity(lpOutBuffer, dwSize, 0) 
        bResults := DllCall("Winhttp.dll\WinHttpQueryHeaders"
                          ,HINTERNET,hRequest
                          ,DWORD,22 ;raw
                          ,LPCWSTR,NULL
                          ,LPVOID, &lpOutBuffer
                          ,"UIntP", dwSize
                          ,LPDWORD, NULL)
    }
    If (!bResults)
        Return % {Body:responseBody,Headers:{},StatusCode:0,StatusText:"",HttpVersion:"",Error:"Receiving responseheaders failed"} ;Msgbox,, hRequest, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    
    VarSetCapacity(lpOutBuffer, -1) ; update the internal string length - otherwise script will crash
    ;;;;;;;;;;;;;;;;;;;;;;;;;
    
    ;Parse received statusline and request headers
    responseHeaders := Object()
    requestLine := Array()
    Loop, parse, lpOutBuffer, `n, `r
    {
        If (!A_LoopField)
            Continue
        If (A_Index = 1) {
            Loop, parse, A_LoopField, %A_Space%
                requestLine[A_Index] := A_LoopField
        } Else
            responseHeaders.Insert(SubStr(A_LoopField,1,InStr(A_LoopField,": ")-1), SubStr(A_LoopField,InStr(A_LoopField,": ")+2))
    }
    responseHttpVersion := requestLine[1]
    statusCode := requestLine[2]
    statusText := requestLine[3]
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    
    If (A_LastError || ErrorLevel)
        Return % {Body:responseBody,Headers:responseHeaders,StatusCode:statusCode,StatusText:statusText,HttpVersion:responseHttpVersion,Error:"An error occurred"} ;Msgbox,, hRequest, LastError: %A_LastError%`nErrorLevel: %ErrorLevel%
    
    Return % {Body:responseBody,Headers:responseHeaders,StatusCode:statusCode,StatusText:statusText,HttpVersion:responseHttpVersion,Error:""}
}

Well, I used the function to upload pictures to 250kb.de and normal files to zippyshare.com
But this involved using content-disposition in the body and was pretty complicated stuff until I managed to automate it:

Code: Select all

HtmlUpload(url,FileNames,AddCDParams:="",AddHeaders:="") {
    static MimeType := {jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",gif:"image/gif"}
    boundary := RandomString(16)    
    Files := Object()
    bodySize := 0
    Loop % FileNames.MaxIndex() {
        filePath := FileNames[A_Index]
        SplitPath, filePath, fileName,, fileExt
        buffer := "--" . boundary . "`r`n"
        buffer .= "Content-Disposition: form-data; name=""file_" . A_Index-1 . """; filename=""" . fileName . """`r`n"
        buffer .= "Content-Type: " . MimeType[fileExt] . "`r`n`r`n"
        buffer .= "`r`n"
        bodySize += StrLen(buffer)
        Files[A_Index] := FileOpen(filePath, "r")
        bodySize += Files[A_Index].Length
    }
    buffer := "--" . boundary
    
    For cdKey, cdValue in AddCDParams
    {
        buffer .=  "`r`nContent-Disposition: form-data; name=""" . cdKey . """`r`n`r`n" 
        buffer .= cdValue . "`r`n"
        buffer .= "--" . boundary
    }
    buffer .= "--"
    bodySize += StrLen(buffer)
    VarSetCapacity(body,bodySize)
    currentPos := 0
    Loop % FileNames.MaxIndex() {
        filePath := FileNames[A_Index]
        SplitPath, filePath, fileName,, fileExt
        VarSetCapacity(buffer,0)
        buffer := "--" . boundary . "`r`n"
        buffer .= "Content-Disposition: form-data; name=""file_" . A_Index-1 . """; filename=""" . fileName . """`r`n"
        buffer .= "Content-Type: " . MimeType[fileExt] . "`r`n`r`n"
        bufferSize := StrLen(buffer)
        StrPut(buffer, &body+currentPos, bufferSize, "CP0")
        currentPos += bufferSize
        
        bufferSize := VarSetCapacity(buffer,Files[A_Index].Length)
        Files[A_Index].RawRead(&buffer, bufferSize)
        DllCall("RtlMoveMemory", "Ptr", &body+currentPos, "Ptr", &buffer, "UInt", bufferSize)
        currentPos += bufferSize
        
        VarSetCapacity(buffer,0)
        buffer :=  "`r`n"
        bufferSize := StrLen(buffer)
        StrPut(buffer, &body+currentPos, bufferSize, "CP0")
        currentPos += bufferSize
    }
    buffer := "--" . boundary
    
    For cdKey, cdValue in AddCDParams
    {
        buffer .=  "`r`nContent-Disposition: form-data; name=""" . cdKey . """`r`n`r`n" 
        buffer .= cdValue . "`r`n"
        buffer .= "--" . boundary
    }
    buffer .= "--"
    bufferSize := StrLen(buffer)
    StrPut(buffer, &body+currentPos, bufferSize, "CP0")
    currentPos += bufferSize
    
    If (!IsObject(headers))
        headers := Object()
    headers["Content-Type"] := "multipart/form-data; boundary=" . boundary
    headers["Content-Length"] := bodySize

    Return HttpRequest(url,"POST",headers,body)
}

RandomString(length,chars:="") {
    If (chars = "")
        chars := "0123456789abcdefghijklmnopqrstuvwxyz"
    charsCount := StrLen(chars)
    Loop %length% {
        Random, num, 1, % StrLen(chars)
        string .= SubStr(chars,num,1)
    }
    Return string
}
Then I just had to reverse engineer the sites a little bit to find out what content-disposition parameters they were expecting and I ended up with this:

Code: Select all

FileUpl_ZippyShare_com(Files) {
    response := HttpRequest("http://zippyshare.com/sites/index_old.jsp")
    If (response.Error)
        MsgBox,, Errors, % "LibError: " response.Error "`nLastError: " A_LastError "`nErrorLevel: " ErrorLevel
    
    RegexMatch(response.body, "\s+var\s+uploadId\s+=\s+'([^']+)';", match)
    uploadId := match1
    RegexMatch(response.body, "\s+var\s+server\s+=\s+'([^']+)';", match)
    server := match1
    uploadUrl := "http://" . server . ".zippyshare.com/upload"
    Random, x, 1, 174
    Random, y, 1, 50
    
    asd := "asdasd"
    response := HtmlUpload(uploadUrl,Files,{"uploadId":uploadId,"x":x,"y":y})
    If (response.Error)
        MsgBox,, Errors, % "LibError: " response.Error "`nLastError: " A_LastError "`nErrorLevel: " ErrorLevel
    RegexMatch(response.body, "(http://[^\.]+\.zippyshare\.com/v/[^\/]+/file\.html)", match)
    return match1    
}
and

Code: Select all

ImgUpl_250kb_de(Files,Scaling:="",duration:="forever") {
    If (!IsObject(Scaling)) {
        Scaling := Array()
        Loop % files.MaxIndex()
            Scaling[A_Index] := "no-scaling"
    }
    If (duration = "")
        duration = "forever"
    
    CdObj := Object()
    Loop % Files.MaxIndex()
        CdObj.Insert("scaling[" . A_Index-1 . "]", scaling[A_Index])
    CdObj.Insert("duration", duration)
    CdObj.Insert("acceptTOS", "1")
    CdObj.Insert("upload", "Hochladen")
    
    response := HtmlUpload("http://250kb.de/upload",Files,CdObj)
    If (response.Error)
        MsgBox,, Errors, % "LibError: " response.Error "`nLastError: " A_LastError "`nErrorLevel: " ErrorLevel
    
    urls := ""
    While (p := RegexMatch(response.body, "U)id=""url-full-[^""]+"" class=""select-on-focus secondary"" value=""(http://250kb.de/u[^""]+)""", match, p?p+1:1)) {
        urls .= match1 . "`n"
    }
    
    urls := SubStr(urls,1,StrLen(urls)-1)
    Return urls
}
Here are two examples on how to use these:

Code: Select all

#Include BrutosHttpRequest.ahk
#Include HttpUpload.ahk
#Include 250kb.ahk

Files := ["C:\Users\Admin\Desktop\Example.jpg"]
Clipboard := ImgUpl_250kb_de(files)
TrayTip, ImageUplaoder, URL was copied to your clipboard!
Sleep, 3000
Return

Code: Select all

#Include BrutosHttpRequest.ahk
#Include HttpUpload.ahk
#Include ZippyShare.ahk

Files := ["C:\Users\Admin\Desktop\Example.jpg"]
Clipboard := FileUpl_ZippyShare_com(files)
TrayTip, FileUplaoder, URL was copied to your clipboard!
Sleep, 3000
Return
edit: corrected some code mistakes. also edited the first post and removed the content-length headers
edit: corrected another code mistake
edit: and another one in the zippyshare example
Last edited by Bruttosozialprodukt on 29 Mar 2015, 13:55, edited 3 times in total.
User avatar
joedf
Posts: 9097
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: [How To] Do logins using the WinHttpRequest COM

Post by joedf » 22 Jul 2014, 11:42

Wow... Now that's quite something..
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
Post Reply

Return to “Tutorials (v1)”