1

Тема: AHK: WinHttp.WinHttpRequest.5.1

С помощью WinHttp.WinHttpRequest.5.1 нужно залить определенную информацию на сайт https://paste.lemonmc.com/
Кто поможет?
    test := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    url:="https://paste.lemonmc.com/"
    test.Open("GET", url, false)
    test.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    test.Send()
Fileread,text,text.txt
И теперь требуется инфу с переменной text залить на сайт

2

Re: AHK: WinHttp.WinHttpRequest.5.1

lexavolksvl, приведите заголовок в соответствие с правилами. Оформите ссылку кодом "url",  код тегом "code". Поставьте точки в конце предложений.

3

Re: AHK: WinHttp.WinHttpRequest.5.1

Используется такой же принцип заливки (функция CreateFormData()):
http://forum.script-coding.com/viewtopic.php?id=13605

4

Re: AHK: WinHttp.WinHttpRequest.5.1

Malcev, тут есть маленькая тонкость. Со страницы нужно сначала получить токен (_token). Он находится в скрытом поле. Без него отправка будет отбиваться. Но что странно - заливка файла проходит без проблем, сайт возвращает URL сохранения, но при переходе по нему получаю ошибку:

+ открыть спойлер

https://i.imgur.com/oZz5UKe.png

Передумал переделывать мир. Пашет и так, ну и ладно. Сделаю лучше свой !

5 (изменено: Malcev, 2018-09-27 17:33:26)

Re: AHK: WinHttp.WinHttpRequest.5.1

Такого типа тонкости обычно везде бывают.

text := "Привет мир!"

HTTP := ComObjCreate("WinHTTP.WinHTTPRequest.5.1")
HTTP.Open("GET", "https://paste.lemonmc.com", true)
HTTP.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
HTTP.SetRequestHeader("Pragma", "no-cache")
HTTP.SetRequestHeader("Cache-Control", "no-cache, no-store")
HTTP.SetRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT")
HTTP.Send()
HTTP.WaitForResponse()
RegexMatch(HTTP.ResponseText, "s)<input name=""_token"".+?value=""(.+?)""", match)
token := match1

objParam := {"_submit": "Paste", "_token": token, "attachment": "", "data": text, "expire": 21600, "language": "text", "password": "", "title": ""}
CreateFormData(PostData, hdr_ContentType, objParam)

HTTP.Open("POST", "https://paste.lemonmc.com/create", true)
HTTP.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko)")
HTTP.SetRequestHeader("Content-Type", hdr_ContentType)
HTTP.SetRequestHeader("Pragma", "no-cache")
HTTP.SetRequestHeader("Cache-Control", "no-cache, no-store")
HTTP.SetRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT")
HTTP.Send(PostData)
HTTP.WaitForResponse()
msgbox % clipboard := HTTP.GetResponseHeader("StickyNotes-Url")
return



; CreateFormData() by tmplinshi, AHK Topic: https://autohotkey.com/boards/viewtopic.php?t=7647
; Thanks to Coco: https://autohotkey.com/boards/viewtopic.php?p=41731#p41731
; Modified version by SKAN, 09/May/2016

CreateFormData(ByRef retData, ByRef retHeader, objParam) {
	New CreateFormData(retData, retHeader, objParam)
}

Class CreateFormData {

	__New(ByRef retData, ByRef retHeader, objParam) {

		Local CRLF := "`r`n", i, k, v, str, pvData
		; Create a random Boundary
		Local Boundary := this.RandomBoundary()
		Local BoundaryLine := "------------------------------" . Boundary

    this.Len := 0 ; GMEM_ZEROINIT|GMEM_FIXED = 0x40
    this.Ptr := DllCall( "GlobalAlloc", "UInt",0x40, "UInt",1, "Ptr"  )          ; allocate global memory

		; Loop input paramters
		For k, v in objParam
		{
			If IsObject(v) {
				For i, FileName in v
				{
					str := BoundaryLine . CRLF
					     . "Content-Disposition: form-data; name=""" . k . """; filename=""" . FileName . """" . CRLF
					     . "Content-Type: " . this.MimeType(FileName) . CRLF . CRLF
          this.StrPutUTF8( str )
          this.LoadFromFile( Filename )
          this.StrPutUTF8( CRLF )
				}
			} Else {
				str := BoundaryLine . CRLF
				     . "Content-Disposition: form-data; name=""" . k """" . CRLF . CRLF
				     . v . CRLF
        this.StrPutUTF8( str )
			}
		}

		this.StrPutUTF8( BoundaryLine . "--" . CRLF )

    ; Create a bytearray and copy data in to it.
    retData := ComObjArray( 0x11, this.Len ) ; Create SAFEARRAY = VT_ARRAY|VT_UI1
    pvData  := NumGet( ComObjValue( retData ) + 8 + A_PtrSize )
    DllCall( "RtlMoveMemory", "Ptr",pvData, "Ptr",this.Ptr, "Ptr",this.Len )

    this.Ptr := DllCall( "GlobalFree", "Ptr",this.Ptr, "Ptr" )                   ; free global memory 

    retHeader := "multipart/form-data; boundary=----------------------------" . Boundary
	}

  StrPutUTF8( str ) {
    Local ReqSz := StrPut( str, "utf-8" ) - 1
    this.Len += ReqSz                                  ; GMEM_ZEROINIT|GMEM_MOVEABLE = 0x42
    this.Ptr := DllCall( "GlobalReAlloc", "Ptr",this.Ptr, "UInt",this.len + 1, "UInt", 0x42 )   
    StrPut( str, this.Ptr + this.len - ReqSz, ReqSz, "utf-8" )
  }
  
  LoadFromFile( Filename ) {
    Local objFile := FileOpen( FileName, "r" )
    this.Len += objFile.Length                     ; GMEM_ZEROINIT|GMEM_MOVEABLE = 0x42 
    this.Ptr := DllCall( "GlobalReAlloc", "Ptr",this.Ptr, "UInt",this.len, "UInt", 0x42 )
    objFile.RawRead( this.Ptr + this.Len - objFile.length, objFile.length )
    objFile.Close()       
  }

	RandomBoundary() {
		str := "0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z"
		Sort, str, D| Random
		str := StrReplace(str, "|")
		Return SubStr(str, 1, 12)
	}

	MimeType(FileName) {
		n := FileOpen(FileName, "r").ReadUInt()
		Return (n        = 0x474E5089) ? "image/png"
		     : (n        = 0x38464947) ? "image/gif"
		     : (n&0xFFFF = 0x4D42    ) ? "image/bmp"
		     : (n&0xFFFF = 0xD8FF    ) ? "image/jpeg"
		     : (n&0xFFFF = 0x4949    ) ? "image/tiff"
		     : (n&0xFFFF = 0x4D4D    ) ? "image/tiff"
		     : "application/octet-stream"
	}

}

6

Re: AHK: WinHttp.WinHttpRequest.5.1

У меня как-то проще вышло:

baseUrl := "https://paste.lemonmc.com/"

http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
http.open("POST", baseUrl . "api/json/create")
http.SetRequestHeader("Content-Type", "application/json")
safeArray := SafeArrayFromString("{""data"":""MsgBox, Hello, World!"",""language"":""autohotkey""}")
http.Send(safeArray)
MsgBox, % Clipboard := RegExReplace(http.responseText, "s).*""id"":\s*""(.+?)"".*", baseUrl . "$1")

SafeArrayFromString(str)  {
   VarSetCapacity(data, size := StrPut(str, "UTF-8"), 0)
   StrPut(str, &data, "UTF-8")
   arr := ComObjArray(VT_UI1 := 0x11, size)
   DllCall("RtlMoveMemory", Ptr, NumGet( ComObjValue(arr) + 8 + A_PtrSize ), Ptr, &data, Ptr, size)
   Return arr
}
Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

7

Re: AHK: WinHttp.WinHttpRequest.5.1

А я и не заметил, что там апи есть.

8

Re: AHK: WinHttp.WinHttpRequest.5.1

Sticky Notes Api
А вообще-то и так работает:

baseUrl := "https://paste.lemonmc.com/"

http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
http.Open("POST", baseUrl . "api/json/create")
http.SetRequestHeader("Content-Type", "application/json")
http.Send("{""data"":""MsgBox, Hello, World!"",""language"":""autohotkey""}")
MsgBox, % Clipboard := RegExReplace(http.responseText, "s).*""id"":\s*""(.+?)"".*", baseUrl . "$1")
Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

9

Re: AHK: WinHttp.WinHttpRequest.5.1

Уже вопрос решен. Всем спасибо кто пытался помочь. Но разобрался сам

10

Re: AHK: WinHttp.WinHttpRequest.5.1

lexavolksvl, а что вы игнорируете замечание модератора?
Так и до бана недалеко.

11

Re: AHK: WinHttp.WinHttpRequest.5.1

Не понимаю, почему RegEx не работает в метке по таймеру. Во втором MsgBox  у меня пусто.


req := ComObjCreate("WinHttp.WinHttpRequest.5.1")
req.Option(6) := 0
req.open("GET", "https://www.autohotkey.com/download/", 1)
req.send()
Sleep 2222 

RegExMatch(req.responseText, "<!--update-->v(.*?) - ", m)
MsgBox % m1

CheckAhkNewVersion()
Return

CheckAhkNewVersion() {
	Static req, att := 0  
	req := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	req.Option(6) := 0
	req.open("GET", "https://www.autohotkey.com/download/", 1)
	req.send()
	SetTimer, lCheckAhkNewVersion, -1000
	Return

	lCheckAhkNewVersion:
		++att
		If (req.Status = 200)
		{
			RegExMatch(req.responseText, "<!--update-->v(.*?) - ", m)
			MsgBox % m1
			Return
		}
		If (att <= 3)
			SetTimer, lCheckAhkNewVersion, -2000
		Return 
}
По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

12 (изменено: Malcev, 2020-10-30 00:46:44)

Re: AHK: WinHttp.WinHttpRequest.5.1

Within a function (unless force-local mode is in effect), any dynamic variable reference such as Array%i% always resolves to a local variable unless no variable of that name exists, in which case a global is used if it exists. If neither exists and the usage requires the variable to be created, it is created as a local variable unless the assume-global mode is in effect. Consequently, a function can create a global array manually (by means such as Array%i% := A_Index) only if it has been defined as an assume-global function.

https://www.autohotkey.com/docs/Functio … nd_globals
Либо выводи таймер за пределы функции и передавай ему req.
Либо используй объект match.
Либо объявляй m1 как глобальную.

13

Re: AHK: WinHttp.WinHttpRequest.5.1

Добавлю для ясности, что метка таймера не является в данном случае частью функции, хотя она и визуально расположена внутри неё.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

14 (изменено: serzh82saratov, 2020-10-30 01:21:01)

Re: AHK: WinHttp.WinHttpRequest.5.1

Malcev
Спасибо, вспомнил что очень давно с этим сталкивался.

А тут не знаешь в чём дело, у меня RegExReplace из строки скопированной из запроса и из самого запроса выдаёт разные результаты.


responseText = 
(  
<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>AutoHotkey Downloads</title>
  <script src="/cdn-cgi/apps/head/21XiSFXBdVHXl7A_izEkLSn9ayc.js"></script><link rel="icon" type="image/ico" href="/favicon.ico">
  <link rel="stylesheet" href="css/style.css">
  <meta name="robots" content="noindex,nofollow">
</head>
<body>

<a href="/"><img src="/static/ahk_logo.svg"></a>
<p>Current version: <a href="../docs/AHKL_ChangeLog.htm"><!--update-->v1.1.33.02 - July 17, 2020<!--/update--></a></p>
<p><a class="install_button" href="ahk-install.exe">Download AutoHotkey Installer</a></p>
<p>Mirror: <a href="https://github.com/Lexikos/AutoHotkey_L/releases">Releases on GitHub</a></p>
<p><a href="ahk.zip">Download AutoHotkey .zip</a></p>
<p><a href="https://github.com/Lexikos/AutoHotkey_L/">Source code on GitHub</a></p>
<p><strong>Note:</strong> The installer also includes an "extract to" function to extract all files without installing. This can be accessed from the installer GUI or <a href="/docs/Program.htm#install">on the command line</a>.</p>

<h2>Other Releases</h2>
<p class="warning"><strong>Note:</strong> Google Safe Browsing sometimes falsely flags these directories as containing "harmful programs". For more information, see <a href="safe.htm">Safe Browsing</a>.</p>
<p><a href="1.1/">AutoHotkey 1.1.*</a> - previously known as AutoHotkey_L.<br>
<a href="1.0/">AutoHotkey 1.0.*</a> - also retroactively known as AutoHotkey Basic, Classic, Vanilla, etc.<br>
<a href="2.0/">AutoHotkey 2.0-a*</a> - see <a href="/v2/">AutoHotkey v2</a>.</p>

<h2>Documentation</h2>
<p><a href="/docs/AutoHotkey.htm">Online - v1.1</a><br>
<a href="https://lexikos.github.io/v2/docs/AutoHotkey.htm">Online - v2.0-alpha</a></p>
Help files in other languages - these are maintained by other volunteers, so are sometimes out of date:
<ul>
  <li><a href="http://ahkcn.sf.net/">Chinese</a> (ä¸æ–‡)</li>
  <li><a href="https://github.com/ahkde/docs/releases/latest">German</a> (Deutsch)</li>
  <li><a href="https://github.com/ahkscript/AHK-Docs_KO/releases/latest">Korean</a> (한êµì–´)</li>
</ul>
<p>English documentation is included in the installer and portable downloads.</p>

<h2>Uninstallation</h2>
<p>If you are looking to uninstall AutoHotkey and you are having trouble doing so, please <a href="/uninstall">click here</a> for detailed instructions (with pictures).</p>

</body>
</html>


)
MsgBox % RegExReplace(responseText, ".*?<!--update-->v(.*?) - .*", "$1")


req := ComObjCreate("WinHttp.WinHttpRequest.5.1")
req.Option(6) := 0
req.open("GET", "https://www.autohotkey.com/download/", 1)
req.send()
Sleep 2222 
MsgBox % RegExReplace(Clipboard := req.responseText, ".*?<!--update-->v(.*?) - .*", "$1")
Return
По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

15

Re: AHK: WinHttp.WinHttpRequest.5.1

teadrinker пишет:

метка таймера не является в данном случае частью функции

А откуда в ней доступ к статическим переменным этой функции?

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

16 (изменено: teadrinker, 2020-10-30 01:23:18)

Re: AHK: WinHttp.WinHttpRequest.5.1

serzh82saratov пишет:

А тут не знаешь в чём дело, у меня RegExReplace из строки скопированной из запроса и из самого запроса выдаёт разные результаты.

Разные переносы строк, добавь опцию s).

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

17

Re: AHK: WinHttp.WinHttpRequest.5.1

DotAll. This causes a period (.) to match all characters including newlines (normally, it does not match newlines). However, when the newline character is at its default of CRLF (`r`n), two dots are required to match it (not one). Regardless of this option, a negative class such as [^a] always matches newlines.

teadrinker
Спасибо, но почему это имеет значение в этом шаблоне, разве (.*) не должно включать всё что угодно, одиночный или двойной, какая разница.

However, when the newline character is at its default of CRLF (`r`n), two dots are required to match it (not one)

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

18

Re: AHK: WinHttp.WinHttpRequest.5.1

Я уже писал об этом баге документации.
Правильно так:
Точка без опции s, не может быть символом `r если после символа `r идет символ `n.

19

Re: AHK: WinHttp.WinHttpRequest.5.1

Часть паттерна .* запинается на первом переносе строк, если он `r`n и не указана опция s).

teadrinker пишет:

Добавлю для ясности, что метка таймера не является в данном случае частью функции, хотя она и визуально расположена внутри неё.

Да, был не прав. Никогда не использую подобные конструкции. Можно упростить:

#Persistent
MyFunc()
Return

MyFunc() {
   static var := "test"
   SetTimer, Timer, -1000
   Return

   Timer:
      RegExMatch(var, "(.)", m)
      MsgBox, % m1
      Return
}

В то же время срабатывает, если объявить m1 глобальной. Для меня такое поведение непонятно, я бы счёл багом.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

20

Re: AHK: WinHttp.WinHttpRequest.5.1

Потестировал, наверное действительно баг.
Напишу на оффоруме.

#Persistent
SetTimer, timer, -1
SetTimer, test, -500
Return

test()
{
   Timer:
   RegExMatch("var", "(.)..", m)
   msgbox % m "`n" m1
   Return
}

21

Re: AHK: WinHttp.WinHttpRequest.5.1

teadrinker пишет:

Часть паттерна .* запинается на первом переносе строк

Скорее не запинается, а работает как описано в №18.

Text = 111`r`n222`r`n___333___`r`n444`r`n555

MsgBox % RegExReplace(Text, ".*(333).*", "$1")
Malcev пишет:

Потестировал, наверное действительно баг.

Да, любопытно.

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

22

Re: AHK: WinHttp.WinHttpRequest.5.1

A function may contain externally-called subroutines such as timers, GUI g-labels, and menu items. ... However, the following limitations apply:
    Such subroutines should use only static and global variables (not locals) if their function is ever called normally. ...
    When a function is entered by a subroutine thread, any references to dynamic variables made by that thread are treated as globals (including commands that create arrays).

https://www.autohotkey.com/docs/Functions.htm#gosub