AutoHotkey Community

It is currently May 26th, 2012, 8:05 pm

All times are UTC [ DST ]




Post new topic Reply to topic  [ 233 posts ]  Go to page Previous  1 ... 4, 5, 6, 7, 8, 9, 10 ... 16  Next

Should a more generic function be released which will include the already available web functions, such as header queries, uri encoding, base encoding, etc ?
yes, i'd like to have one function to get all neccessary http functionalities in one instead of collecting each for my own
no, i prefer collecting the functions i need
neither nor ... explained in post
You may select 1 option

View results
Author Message
 Post subject:
PostPosted: July 5th, 2009, 5:35 pm 
Offline

Joined: March 27th, 2009, 12:46 pm
Posts: 76
Location: Dublin, IE
I'm using httpQuery with XBMC's http server and I'm not getting back the result I need. I've listed below my AHK code, the html contents when saved using a web browser, and the results when using UrlDownloadToFile.

httpQuery code:
Code:
sAddress  := "http://localhost"
nPort     := "8001"
sUsername := "XBMC"
sPassword := "Password"
sCmd      := "getcurrentlyplaying"
sURL      := "http://" . sUsername . ":" . sPassword . "@"
            . RegExReplace(sAddress,"http://(.*?)") . ":" . nPort
            . "/xbmcCmds/xbmcHttp?command=" . sCmd

len := httpQuery(buffer:="",sURL)
VarSetCapacity(buffer,-1)
MsgBox, % buffer "`n" len


httpQuery results
httpQuery wrote:
len = 4
buffer = HTT


UrlDownloadToFile code:
Code:
sAddress  := "http://localhost"
nPort     := "8001"
sUsername := "XBMC"
sPassword := "Password"
sCmd      := "getcurrentlyplaying"
sURL      := "http://" . sUsername . ":" . sPassword . "@"
            . RegExReplace(sAddress,"http://(.*?)") . ":" . nPort
            . "/xbmcCmds/xbmcHttp?command=" . sCmd

UrlDownloadToFile, %sURL%, junk.txt
FileRead, sData, junk.txt
FileDelete, junk.txt
MsgBox, % sData

UrlDownloadToFile result:
UrlDownloadToFile wrote:
<html>
<li>Filename:E:\My Videos\TV Shows\Knight Rider (2008)\Knight Rider (2008) - S01E10 - Don't Stop The Knight.avi
<li>PlayStatus:Paused
<li>VideoNo:0
<li>Type:Video
<li>Show Title:Knight Rider
<li>Title:Don't Stop the Knight (1)
<li>Plot:Mike and KITT are sent on an endless string of mini-missions by a crazy terrorist in exchange to keep Ambassador Olara Kumali alive, but they soon realize that they are part of a bigger plan. Trying to outsmart the terrorist, Rivai and a team of FBI agents find themselves in an explosive situation. Meanwhile, Sarah and Dr. Graiman try to fix a sick robot.
<li>Rating:7.0 ( votes)
<li>First Aired:2009-01-07
<li>Year:2009
<li>Season:1
<li>Episode:10
<li>Thumb:defaultVideoCover.png
<li>Time:00:36
<li>Duration:40:29
<li>Percentage:1
<li>File size:366344192
<li>Changed:False</html>

html file saved from browser:
Code:
<!-- saved from url=(0080)http://XBMC:Ncw0483@localhost:8001/xbmcCmds/xbmcHttp?command=getcurrentlyplaying -->
<HTML><HEAD><META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></HEAD><BODY><LI>Filename:E:\My Videos\TV Shows\Knight Rider (2008)\Knight Rider (2008) - S01E10 - Don't Stop The Knight.avi
</LI><LI>PlayStatus:Playing
</LI><LI>VideoNo:0
</LI><LI>Type:Video
</LI><LI>Show Title:Knight Rider
</LI><LI>Title:Don't Stop the Knight (1)
</LI><LI>Plot:Mike and KITT are sent on an endless string of mini-missions by a crazy terrorist in exchange to keep Ambassador Olara Kumali alive, but they soon realize that they are part of a bigger plan. Trying to outsmart the terrorist, Rivai and a team of FBI agents find themselves in an explosive situation. Meanwhile, Sarah and Dr. Graiman try to fix a sick robot.
</LI><LI>Rating:7.0 ( votes)
</LI><LI>First Aired:2009-01-07
</LI><LI>Year:2009
</LI><LI>Season:1
</LI><LI>Episode:10
</LI><LI>Thumb:defaultVideoCover.png
</LI><LI>Time:00:11
</LI><LI>Duration:40:29
</LI><LI>Percentage:0
</LI><LI>File size:366344192
</LI><LI>Changed:False
</LI></BODY></HTML>


Any help would be appreciated

_________________
My Scripts


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 10th, 2009, 2:49 pm 
Offline

Joined: July 9th, 2009, 9:25 pm
Posts: 120
Voltron43 wrote:
I'm using httpQuery with XBMC's http server and I'm not getting back the result I need. I've listed below my AHK code, the html contents when saved using a web browser, and the results when using UrlDownloadToFile.


What status line (something like HTTP/xx 200 in headers) is that server returning? the protocol version is hard-coded in httpQuery as "1.1" so if it returns anything other than that (like HTTP/1.0), it'll return incorrect result.
You can check it by adding a msgbox, %RetValue% line just before the "; Strip protocol.." comment line in httpQuery.ahk.


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 10th, 2009, 11:37 pm 
Offline

Joined: March 27th, 2009, 12:46 pm
Posts: 76
Location: Dublin, IE
temp01 wrote:
What status line (something like HTTP/xx 200 in headers) is that server returning? the protocol version is hard-coded in httpQuery as "1.1" so if it returns anything other than that (like HTTP/1.0), it'll return incorrect result.


The returned header when using the option...

Code:
httpQueryOps := "storeHeader"

header wrote:
HTTP/1.0 200 OK
Server: GoAhead-Webs
Pragma: no-cache
Cache-control: no-cache
Content-Type: text/html


Is there anything I can do to fix this?

Thanks

_________________
My Scripts


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 11th, 2009, 3:58 am 
Offline

Joined: July 9th, 2009, 9:25 pm
Posts: 120
Voltron43 wrote:
temp01 wrote:
What status line (something like HTTP/xx 200 in headers) is that server returning? the protocol version is hard-coded in httpQuery as "1.1" so if it returns anything other than that (like HTTP/1.0), it'll return incorrect result.


The returned header when using the option...

Code:
httpQueryOps := "storeHeader"

header wrote:
HTTP/1.0 200 OK
...


Is there anything I can do to fix this?


Yes, replace line 140 in httpQuery.ahk:
Code:
RetValue := RegExReplace(RetValue,"\Q" ProVer "\E\s+")

with:
Code:
RetValue := RegExReplace(RetValue,"HTTP/1\.[01]\s+")


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 11th, 2009, 4:54 am 
Offline

Joined: November 1st, 2007, 10:03 pm
Posts: 885
Yay, temps on the forum


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 11th, 2009, 1:51 pm 
Offline

Joined: March 27th, 2009, 12:46 pm
Posts: 76
Location: Dublin, IE
temp01 wrote:
Yes, replace line 140 in httpQuery.ahk:
Code:
RetValue := RegExReplace(RetValue,"\Q" ProVer "\E\s+")

with:
Code:
RetValue := RegExReplace(RetValue,"HTTP/1\.[01]\s+")


It now works, thanks!

_________________
My Scripts


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 12th, 2009, 6:51 pm 
Hello, I have some problem with the code! I want to upload files at rapidshare's site, and I tryied to modify the Imageshack upload code from the first page

I tryied to sniff the HTTP requests with the HTTP Analyzer, and I have that results:

With RapidUploader
http://pastebin.com/m64a83fa2

With Autohotkey
http://pastebin.com/m2babb235

The Script Code:
Code:
; exmpl.imageshack.httpQuery.ahk
; This example uploads an image and constructs a multipart/form-data Type
; for fileuploading and returns the XML which is returned to show the stored Imagepath
   FileSelectFile,image
   image1 := image
   FileGetSize,size,%image%
   SplitPath,image,OFN
   FileRead,img,%image%
   VarSetCapacity(placeholder,size,32)
   boundary := makeProperBoundary()
;   post:="--" boundary "`ncontent-disposition: form-data; name=""MAX_FILE_SIZE""`n`n"
;      . "1048576`n--" boundary "`ncontent-disposition: form-data; name=""xml""`n`nyes`n--"
;      . boundary "`ncontent-disposition: form-data; name=""fileupload""; filename="""
;      . ofn """`nContent-type: " MimeType(img) "`nContent-Transfer-Encoding: binary`n`n"
;      . placeholder "`n--" boundary "--"
   post:= "----------" boundary "`nContent-Disposition: form-data; name=""rsapi_v1""`n`n"
      . "1`n----------" boundary "`nContent-Disposition: form-data; name=""filecontent""; filename="""
      . image1 """`nContent-Type: multipart/form-data`nContent-Transfer-Encoding: binary`n`n"
      . placeholder "`n----------" boundary "`nContent-Disposition: form-data; name=""freeaccountid"""
      . "`n`nUsername`n----------" boundary "`nContent-Disposition: form-data; name=""password"""
      . "`n`n...----------" boundary "--"
     
   headers:= "Connection: Keep-Alive`nContent-type: multipart/form-data; boundary=--------" boundary "`nContent-Length: " strlen(post)
   msgbox %headers%
   DllCall("RtlMoveMemory","uInt",(offset:=&post+strlen(post)-strlen(Boundary)-size-5)
         ,"uInt",&img,"uInt",size)
   size := httpQuery(result:="","http://rs202tl.rapidshare.com/cgi-bin/upload.cgi",post,headers)
   msgbox %size%
   VarSetCapacity(result,-1)
   Gui,Add,Edit,w800 h600, % result
   Gui,Show
return

GuiClose:
GuiEscape:
   ExitApp

makeProperBoundary(){
   Loop,9
      n .= chr(48+a_index)
   n .= "0123456789"
   Loop,% 15 {
      Random,rnd,1,% StrLen(n)
      Random,UL,0,1
      b .= RegExReplace(SubStr(n,rnd,1),".$","$" (round(UL)? "U":"L") "0")
   }
   Return b
}

MimeType(ByRef Binary) {
   MimeTypes:="424d image/bmp|4749463 image/gif|ffd8ffe image/jpeg|89504e4 image/png|4657530"
          . " application/x-shockwave-flash|49492a0 image/tiff"
   @:="0123456789abcdef"
   Loop,8
      hex .= substr(@,(*(a:=&Binary-1+a_index)>>4)+1,1) substr(@,((*a)&15)+1,1)
   Loop,Parse,MimeTypes,|
      if ((substr(hex,1,strlen(n:=RegExReplace(A_Loopfield,"\s.*"))))=n)
         Mime := RegExReplace(A_LoopField,".*?\s")
   Return (Mime!="") ? Mime : "application/octet-stream"
}

; httpQuery-0-3-4.ahk
httpQuery(byref Result, lpszUrl, POSTDATA="", HEADERS="")
{   ; v0.3.4 (w) Sep, 8 2008 by Heresy & derRaphael / zLib-Style release   
   ; currently the verbs showHeader, storeHeader, and updateSize are supported in httpQueryOps
   ; in case u need a different UserAgent, Proxy, ProxyByPass, Referrer, and AcceptType just
   ; specify them as global variables - mind the varname for referrer is httpQueryReferer [sic].
   ; Also if any special dwFlags are needed such as INTERNET_FLAG_NO_AUTO_REDIRECT or cache
   ; handling this might be set using the httpQueryDwFlags variable as global
   global httpQueryOps, httpAgent, httpProxy, httpProxyByPass, httpQueryReferer, httpQueryAcceptType
       , httpQueryDwFlags
   ; Get any missing default Values
   defaultOps =
   (LTrim Join|
      httpAgent=RapidLoader[v1.99953]|httpProxy=0|httpProxyByPass=0|INTERNET_FLAG_SECURE=0x00800000
      SECURITY_FLAG_IGNORE_UNKNOWN_CA=0x00000100|SECURITY_FLAG_IGNORE_CERT_CN_INVALID=0x00001000
      SECURITY_FLAG_IGNORE_CERT_DATE_INVALID=0x00002000|SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE=0x00000200
      INTERNET_OPEN_TYPE_PROXY=3|INTERNET_OPEN_TYPE_DIRECT=1|INTERNET_SERVICE_HTTP=3
   )
   Loop,Parse,defaultOps,|
   {
      RegExMatch(A_LoopField,"(?P<Option>[^=]+)=(?P<Default>.*)",http)
      if StrLen(%httpOption%)=0
         %httpOption% := httpDefault
   }

   ; Load Library
   hModule := DllCall("LoadLibrary", "Str", "WinINet.Dll")

   ; SetUpStructures for URL_COMPONENTS / needed for InternetCrackURL
   ; http://msdn.microsoft.com/en-us/library/aa385420(VS.85).aspx
   offset_name_length:= "4-lpszScheme-255|16-lpszHostName-1024|28-lpszUserName-1024|"
                  . "36-lpszPassword-1024|44-lpszUrlPath-1024|52-lpszExtrainfo-1024"
   VarSetCapacity(URL_COMPONENTS,60,0)
   ; Struc Size               ; Scheme Size                  ; Max Port Number
   NumPut(60,URL_COMPONENTS,0), NumPut(255,URL_COMPONENTS,12), NumPut(0xffff,URL_COMPONENTS,24)
   
   Loop,Parse,offset_name_length,|
   {
      RegExMatch(A_LoopField,"(?P<Offset>\d+)-(?P<Name>[a-zA-Z]+)-(?P<Size>\d+)",iCU_)
      VarSetCapacity(%iCU_Name%,iCU_Size,0)
      NumPut(&%iCU_Name%,URL_COMPONENTS,iCU_Offset)
      NumPut(iCU_Size,URL_COMPONENTS,iCU_Offset+4)
   }

   ; Split the given URL; extract scheme, user, pass, authotity (host), port, path, and query (extrainfo)
   ; http://msdn.microsoft.com/en-us/library/aa384376(VS.85).aspx
   DllCall("WinINet\InternetCrackUrlA","Str",lpszUrl,"uInt",StrLen(lpszUrl),"uInt",0,"uInt",&URL_COMPONENTS)

   ; Update variables to retrieve results
   Loop,Parse,offset_name_length,|
   {
      RegExMatch(A_LoopField,"-(?P<Name>[a-zA-Z]+)-",iCU_)
      VarSetCapacity(%iCU_Name%,-1)
   }
   nPort:=NumGet(URL_COMPONENTS,24,"uInt")
   
   ; Import any set dwFlags
   dwFlags := httpQueryDwFlags
   ; For some reasons using a selfsigned https certificates doesnt work
   ; such as an own webmin service - even though every security is turned off
   ; https with valid certificates works when
   if (lpszScheme = "https")
      dwFlags |= (INTERNET_FLAG_SECURE|SECURITY_FLAG_IGNORE_CERT_CN_INVALID
               |SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE)

   ; Check for Header and drop exception if unknown or invalid URL
   if (lpszScheme="unknown") {
      Result := "ERR: No Valid URL supplied."
      Return StrLen(Result)
   }

   ; Initialise httpQuery's use of the WinINet functions.
   ; http://msdn.microsoft.com/en-us/library/aa385096(VS.85).aspx
   hInternet := DllCall("WinINet\InternetOpenA"
                  ,"Str",httpAgent,"UInt"
                  ,(httpProxy != 0 ?  INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_DIRECT )
                  ,"Str",httpProxy,"Str",httpProxyBypass,"Uint",0)

   ; Open HTTP session for the given URL
   ; http://msdn.microsoft.com/en-us/library/aa384363(VS.85).aspx
   hConnect := DllCall("WinINet\InternetConnectA"
                  ,"uInt",hInternet,"Str",lpszHostname, "Int",nPort
                  ,"Str",lpszUserName, "Str",lpszPassword,"uInt",INTERNET_SERVICE_HTTP
                  ,"uInt",0,"uInt*",0)

   ; Do we POST? If so, check for header handling and set default
   if (Strlen(POSTDATA)>0) {
      HTTPVerb:="POST"
      if StrLen(Headers)=0
         Headers:="Content-Type: application/x-www-form-urlencoded"
   } else ; otherwise mode must be GET - no header defaults needed
      HTTPVerb:="GET"   

   ; Form the request with proper HTTP protocol version and create the request handle
   ; http://msdn.microsoft.com/en-us/library/aa384233(VS.85).aspx
   hRequest := DllCall("WinINet\HttpOpenRequestA"
                  ,"uInt",hConnect,"Str",HTTPVerb,"Str",lpszUrlPath . lpszExtrainfo
                  ,"Str",ProVer := "HTTP/1.1", "Str",httpQueryReferer,"Str",httpQueryAcceptTypes
                  ,"uInt",dwFlags,"uInt",Context:=0 )

   ; Send the specified request to the server
   ; http://msdn.microsoft.com/en-us/library/aa384247(VS.85).aspx
   sRequest := DllCall("WinINet\HttpSendRequestA"
                  , "uInt",hRequest,"Str",Headers, "uInt",Strlen(Headers)
                  , "Str",POSTData,"uInt",Strlen(POSTData))

   VarSetCapacity(header, 2048, 0)  ; max 2K header data for httpResponseHeader
   VarSetCapacity(header_len, 4, 0)
   
   ; Check for returned server response-header (works only _after_ request been sent)
   ; http://msdn.microsoft.com/en-us/library/aa384238.aspx
   Loop, 5
     if ((headerRequest:=DllCall("WinINet\HttpQueryInfoA","uint",hRequest
      ,"uint",21,"uint",&header,"uint",&header_len,"uint",0))=1)
      break

   If (headerRequest=1) {
      VarSetCapacity(res,headerLength:=NumGet(header_len),32)
      DllCall("RtlMoveMemory","uInt",&res,"uInt",&header,"uInt",headerLength)
      Loop,% headerLength
         if (*(&res-1+a_index)=0) ; Change binary zero to linefeed
            NumPut(Asc("`n"),res,a_index-1,"uChar")
      VarSetCapacity(res,-1)
   } else
      res := "timeout"

   ; Get 1st Line of Full Response
   Loop,Parse,res,`n,`r
   {
      RetValue := A_LoopField
      break
   }
   
   ; No Connection established - drop exception
   If (RetValue="timeout") {
      html := "Error: timeout"
      return -1
   }
   ; Strip protocol version from return value
   RetValue := RegExReplace(RetValue,"\Q" ProVer "\E\s+")
   
    ; List taken from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
   HttpRetCodes := "100=Continue|101=Switching Protocols|102=Processing (WebDAV) (RFC 2518)|"
              . "200=OK|201=Created|202=Accepted|203=Non-Authoritative Information|204=No"
              . " Content|205=Reset Content|206=Partial Content|207=Multi-Status (WebDAV)"
              . "|300=Multiple Choices|301=Moved Permanently|302=Found|303=See Other|304="
              . "Not Modified|305=Use Proxy|306=Switch Proxy|307=Temporary Redirect|400=B"
              . "ad Request|401=Unauthorized|402=Payment Required|403=Forbidden|404=Not F"
              . "ound|405=Method Not Allowed|406=Not Acceptable|407=Proxy Authentication "
              . "Required|408=Request Timeout|409=Conflict|410=Gone|411=Length Required|4"
              . "12=Precondition Failed|413=Request Entity Too Large|414=Request-URI Too "
              . "Long|415=Unsupported Media Type|416=Requested Range Not Satisfiable|417="
              . "Expectation Failed|418=I'm a teapot (RFC 2324)|422=Unprocessable Entity "
              . "(WebDAV) (RFC 4918)|423=Locked (WebDAV) (RFC 4918)|424=Failed Dependency"
              . " (WebDAV) (RFC 4918)|425=Unordered Collection (RFC 3648)|426=Upgrade Req"
              . "uired (RFC 2817)|449=Retry With|500=Internal Server Error|501=Not Implem"
              . "ented|502=Bad Gateway|503=Service Unavailable|504=Gateway Timeout|505=HT"
              . "TP Version Not Supported|506=Variant Also Negotiates (RFC 2295)|507=Insu"
              . "fficient Storage (WebDAV) (RFC 4918)|509=Bandwidth Limit Exceeded|510=No"
              . "t Extended (RFC 2774)"
   
   ; Gather numeric response value
   RetValue := SubStr(RetValue,1,3)
   
   ; Parse through return codes and set according informations
   Loop,Parse,HttpRetCodes,|
   {
      HttpReturnCode := SubStr(A_LoopField,1,3)    ; Numeric return value see above
      HttpReturnMsg  := SubStr(A_LoopField,5)      ; link for additional information
      if (RetValue=HttpReturnCode) {
         RetMsg := HttpReturnMsg
         break
      }
   }

   ; Global HttpQueryOps handling
   if strlen(HTTPQueryOps)>0 {
      ; Show full Header response (usefull for debugging)
      if (instr(HTTPQueryOps,"showHeader"))
         MsgBox % res
      ; Save the full Header response in a global Variable
      if (instr(HTTPQueryOps,"storeHeader"))
         global HttpQueryHeader := res
      ; Check for size updates to export to a global Var
      if (instr(HTTPQueryOps,"updateSize")) {
         Loop,Parse,res,`n
            If RegExMatch(A_LoopField,"Content-Length:\s+?(?P<Size>\d+)",full) {
               global HttpQueryFullSize := fullSize
               break
            }
         if (fullSize+0=0)
            HttpQueryFullSize := "size unavailable"
      }
   }

   ; Check for valid codes and drop exception if suspicious
   if !(InStr("100 200 201 202 302",RetValue)) {
      Result := RetValue " " RetMsg
      return StrLen(Result)
   }

   VarSetCapacity(BytesRead,4,0)
   fsize := 0
   Loop            ; the receiver loop - rewritten in the need to enable
   {               ; support for larger file downloads
      bc := A_Index
      VarSetCapacity(buffer%bc%,1024,0) ; setup new chunk for this receive round
      ReadFile := DllCall("wininet\InternetReadFile"
                  ,"uInt",hRequest,"uInt",&buffer%bc%,"uInt",1024,"uInt",&BytesRead)
      ReadBytes := NumGet(BytesRead)    ; how many bytes were received?
      If ((ReadFile!=0)&&(!ReadBytes))  ; we have had no error yet and received no more bytes
         break                         ; we must be done! so lets break the receiver loop
      Else {
         fsize += ReadBytes            ; sum up all chunk sizes for correct return size
         sizeArray .= ReadBytes "|"
      }
      if (instr(HTTPQueryOps,"updateSize"))
         Global HttpQueryCurrentSize := fsize
   }
   sizeArray := SubStr(sizeArray,1,-1)   ; trim last PipeChar
   
   VarSetCapacity(result,fSize+1,0)      ; reconstruct the result from above generated chunkblocks
   Dest := &result                       ; to a our ByRef result variable
   Loop,Parse,SizeArray,|
      DllCall("RtlMoveMemory","uInt",Dest,"uInt",&buffer%A_Index%,"uInt",A_LoopField)
      , Dest += A_LoopField
       
   DllCall("WinINet\InternetCloseHandle", "uInt", hRequest)   ; close all opened
   DllCall("WinINet\InternetCloseHandle", "uInt", hInternet)
   DllCall("WinINet\InternetCloseHandle", "uInt", hConnect)
   DllCall("FreeLibrary", "UInt", hModule)                    ; unload the library
   return fSize                          ; return the size - strings need update via VarSetCapacity(res,-1)
}


Is that something that I do it wrong?
Thank you for any help.


Report this post
Top
  
Reply with quote  
 Post subject:
PostPosted: July 12th, 2009, 9:15 pm 
Offline

Joined: December 4th, 2006, 10:35 am
Posts: 561
Location: Galil, Israel
well, just glancing over, you've not tracked the MimeType....

doesn't look like you've set capacity on your post before doing buffer move, etc. (well, on 2nd look, you've got placeholder but looks in wrong place, etc.).

_________________
Joyce Jamce


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 12th, 2009, 11:46 pm 
Offline

Joined: January 9th, 2009, 10:42 pm
Posts: 104
I am a little noob.. Could you give me more details or an example?


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 13th, 2009, 4:35 am 
Offline

Joined: July 9th, 2009, 9:25 pm
Posts: 120
I wrote a function to generate the ugly multipart/form-data POST body:
Code:
; a function to generate multipart/form-data post body
; see http://www.autohotkey.com/forum/viewtopic.php?p=281173#281173
Generate_POST_Body(fields, ByRef postbody, ByRef headers){
   ; generate boundary
   static chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
   boundary = --
   Loop, 8 {
      Random, RChar, 1, % StrLen(chars)
      boundary .= SubStr(chars, RChar, 1)
   }

   ; generate postbody
   #LTrim
   postbody =
   Loop, Parse, fields, `n, `r%A_Space%%A_Tab%
   {
      if RegExMatch(A_LoopField, "i)(?<name>.+?)=(?<isFile>@)?(?<val>.+)", field_)
      {
         postbody = %postbody%
            (Join`r`n
               --%boundary%
               Content-Disposition: form-data; name="%field_name%"
            )
         if field_isFile and FileExist(field_val)
         {
            FileRead, file, %field_val%
               fileType := MimeType(file)
            SplitPath, field_val, filename
            FileGetSize, fileSize, %field_val%
            VarSetCapacity(placeholder, fileSize, 32)

            postbody = %postbody%; filename="%filename%"
               (Join`r`n
                  
                  Content-Type: %fileType%
                  Content-Transfer-Encoding: Binary
               )
            field_val := placeholder
         }
         postbody .= "`r`n`r`n" . field_val . "`r`n"
      }
   }
   postbody .= "--" boundary "--`r`n"
   #LTrim Off
   
   ; generate headers
   headers .= (StrLen(headers) ? "`r`n" : "")
      . "Content-type: multipart/form-data; boundary=" boundary "`r`n"
      . "Content-Length: " strlen(postbody)

   if field_isFile
      DllCall("RtlMoveMemory"
      , "uInt", (offset:=&postbody+strlen(postbody)-strlen(boundary)-fileSize-8)
      , "uInt", &file
      , "uInt", filesize)
   return boundary
}

MimeType(ByRef Binary) {
   MimeTypes:="424d image/bmp|4749463 image/gif|ffd8ffe image/jpeg|89504e4 image/png|4657530"
          . " application/x-shockwave-flash|49492a0 image/tiff"
   @:="0123456789abcdef"
   Loop,8
      hex .= substr(@,(*(a:=&Binary-1+a_index)>>4)+1,1) substr(@,((*a)&15)+1,1)
   Loop,Parse,MimeTypes,|
      if ((substr(hex,1,strlen(n:=RegExReplace(A_Loopfield,"\s.*"))))=n)
         Mime := RegExReplace(A_LoopField,".*?\s")
   Return (Mime!="") ? Mime : "application/octet-stream"
}

I used the fileuploading code from the imageshack example in the first post of this topic.

Just pass name=value`nname=value etc.. to the function in the first parameter and it'll update the 2nd and 3rd parameters/variables with the postbody and headers.
To upload a file, prefix the filename with @ (see example below). Currently, you can upload just one file and you must specify it as the last post option.

Example - upload a file to rapidshare using the rapidshare api:
Code:
httpQuery(result:="","http://rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver_v1")
  VarSetCapacity(result, -1)
  $url = http://rs%result%.rapidshare.com/cgi-bin/upload.cgi

post =
  (
    rsapi_v1=1
    filecontent=@C:\Temp\Somefile.db
  )
Generate_POST_Body(post, post, headers)

httpQuery(result:="", $url, post, headers)
  VarSetCapacity(result,-1)
  msgbox % result

and Upload to ImageShack with the help of Generate_POST_Body:
Code:
FileSelectFile, File
If ErrorLevel
   ExitApp

post=
   (
      MAX_FILE_SIZE=1048576
      xml=yes
      fileupload=@%file%
   )
Generate_POST_Body(post, post, headers)

size := httpQuery(result:="", "http://www.imageshack.us/index.php", post, headers)
VarSetCapacity(result,-1)

msgbox % result


Last edited by temp01 on July 13th, 2009, 12:47 pm, edited 1 time in total.

Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 13th, 2009, 10:54 am 
Offline

Joined: January 9th, 2009, 10:42 pm
Posts: 104
Thank you for your help! The script upload the file! My last problem is with the account login..

I tryied to do that:

Code:
post =
  (
    rsapi_v1=1
    filecontent=@C:\tesmp.txt
    freeaccountid=username
    password=password
  )


with HTTP Analyser, I get that results:

Official RapidUploader:

Code:
----------071209200906640
Content-Disposition: form-data; name="freeaccountid"
 
**USERNAME**
----------071209200906640
Content-Disposition: form-data; name="password"
 
**PASS**
----------071209200906640--


AutohotKey Script:

Code:
----Z3QdWERM
Content-Disposition: form-data; name="freeaccountid"

USERNAME
----Z3QdWERM
Content-Disposition: form-data; name="password"

PASSWORD
----Z3QdWERM--


But the file it is not uploaded to my account..


Currently, you can upload just one file and you must specify it as the last post option.

I didn't read that line! Now it is ok the script, and it is upload the file :)


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 13th, 2009, 11:17 am 
Offline

Joined: January 9th, 2009, 10:42 pm
Posts: 104
The last problem that I find is with text files. The Script posts the Conent of file, and at the end, the bountary code.. :?

http://rs257.rapidshare.com/files/25528 ... e_Text.txt


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 13th, 2009, 12:48 pm 
Offline

Joined: July 9th, 2009, 9:25 pm
Posts: 120
JimKarvo wrote:
The last problem that I find is with text files. The Script posts the Conent of file, and at the end, the bountary code.. :?

bah.. stupid rapidshare.. I already had to change a few things when I was writing the rapidshare example and it didn't work :S . Anyway, fixed now; just copy/paste the functions again.


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 14th, 2009, 1:27 am 
Offline

Joined: January 9th, 2009, 10:42 pm
Posts: 104
Thank you! the code works fine! :D

Also, is it possible to see eg the percent of the upload? Or how many bytes has the script uploaded at the current session?

EDIT:

I tryied to upload a file about 80 mb, but It isn't uploaded..The script got an error for maxmem.. I chacge the maxmem to 250 but it is not upload.. Are there any bug with big files?


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: July 14th, 2009, 2:25 am 
Offline

Joined: July 9th, 2009, 9:25 pm
Posts: 120
JimKarvo wrote:
Thank you! the code works fine! :D

Also, is it possible to see eg the percent of the upload? Or how many bytes has the script uploaded at the current session?

See Example #3 in the first post of this thread (shows the progress in a tooltip)

JimKarvo wrote:
I tryied to upload a file about 80 mb, but It isn't uploaded..The script got an error for maxmem.. I chacge the maxmem to 250 but it is not upload.. Are there any bug with big files?

hmm, no. The function just generates the string for you and it should work fine no matter how big the file is. What error did you get (after changing maxmem) ?


Report this post
Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 233 posts ]  Go to page Previous  1 ... 4, 5, 6, 7, 8, 9, 10 ... 16  Next

All times are UTC [ DST ]


Who is online

Users browsing this forum: Exabot [Bot], notsoobvious, Uberi and 17 guests


You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Powered by phpBB® Forum Software © phpBB Group