求助AutoHotKey里调用WinHttp.WinHttpRequest.5.1中body内容格式

遇到了问题?请先进行搜索(中文和英文),然后在此提问

Moderators: tmplinshi, arcticir

0772boy
Posts: 1
Joined: 22 May 2018, 08:19

求助AutoHotKey里调用WinHttp.WinHttpRequest.5.1中body内容格式

06 Jan 2019, 01:01

起因,想自己用一下百度ORC文字识别

经过,按照网上教程各步骤摸清楚了API的用法,也用Postman调试成功了如图:

Image


然后,用AHK写代码的时候,获取token的步骤一切正常:

Image



但是,到识别的时候就出错了:

Image

Image


最后一次修改是按照这里(https://blog.csdn.net/loyuu/article/details/12755313)的格式:


“request.send (data) '发送数据”

请问一下我到底哪里没写对?

如蒙指教不甚感激。

返回的错误提示内容我知道,但是图片格式是正确的,JPG图片的base64编码,用postman测试过了的,post返回的结果是正确的(见附件插图)

我分别用windows自带的编码功能转码出来的内容和我网上找的在线编码转出来的内容对比,是一致的,然后base64编码内容也能还原成图片

所以我觉得大概是我调用WinHttp.WinHttpRequest.5.1写的代码格式不正确但是又找不到其他的实例
tmplinshi
Posts: 1604
Joined: 01 Oct 2013, 14:57

Re: 求助AutoHotKey里调用WinHttp.WinHttpRequest.5.1中body内容格式

31 Jan 2019, 05:15

按照文档中所说,access_token 参数应该是要放在 URL 中的,而你放到 body 中去了。另外 Base64 数据要进行 UriEncode。

Code: Select all

; 接入流程
; http://ai.baidu.com/docs#/Begin/top
apiKey := "这里替换为你的apiKey"
secretKey := "这里替换为你的secretKey"

; 获取Access Token
; http://ai.baidu.com/docs#/Auth/top
whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" apiKey "&client_secret=" secretKey)
whr.Send()
ret := Jxon_Load(whr.ResponseText)
if !ret.access_token
	throw ret.error "`n" ret.error_description

; 通用文字识别
whr.Open("POST", "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" ret.access_token)
whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")

b64Data := Base64Enc_FromFile("test.png")
body := "image=" UriEncode(b64Data) "&language_type=CHN_ENG"
whr.Send(body)

MsgBox % GetWinHttpText(whr) ; 结果要转换成UTF-8,不然会显示乱码
ExitApp

GetWinHttpText(objWinHttp, encoding := "UTF-8") {
	ado := ComObjCreate("adodb.stream")
	ado.Type     := 1 ; adTypeBinary = 1
	ado.Mode     := 3 ; adModeReadWrite = 3
	ado.Open()
	ado.Write(objWinHttp.ResponseBody)
	ado.Position := 0
	ado.Type     := 2 ; adTypeText = 2
	ado.Charset  := encoding
	return ado.ReadText(), ado.Close()
}
https://github.com/tmplinshi/BaiduOCR-Test.ahk

Return to “请求帮助”

Who is online

Users browsing this forum: No registered users and 19 guests