Delphi:使用带有IdHTTP的Google URL Shortener – 400 Bad Requ
发布时间:2020-12-15 09:25:08 所属栏目:大数据 来源:网络整理
导读:我正在尝试通过Delphi中的API访问URL Shortener( http://goo.gl/). 但是,我得到的唯一结果是:HTTP / 1.0 400错误请求(原因:parseError) 这是我的代码(在一个带有Button1,Memo1和IdHTTP1的表单上,它有IdSSLIOHandlerSocketOpenSSL1作为它的IOHandler.我从ht
我正在尝试通过Delphi中的API访问URL Shortener(
http://goo.gl/).
但是,我得到的唯一结果是:HTTP / 1.0 400错误请求(原因:parseError) 这是我的代码(在一个带有Button1,Memo1和IdHTTP1的表单上,它有IdSSLIOHandlerSocketOpenSSL1作为它的IOHandler.我从http://indy.fulgan.com/SSL/获得了必要的32位OpenSSL DLL并将它们放在.exe的目录中): procedure TFrmMain.Button1Click(Sender: TObject); var html,actionurl: String; makeshort: TStringList; begin try makeshort := TStringList.Create; actionurl := 'https://www.googleapis.com/urlshortener/v1/url'; makeshort.Add('{"longUrl": "http://slashdot.org/stories"}'); IdHttp1.Request.ContentType := 'application/json'; //IdHTTP1.Request.ContentEncoding := 'UTF-8'; //Using this gives error 415 html := IdHTTP1.Post(actionurl,makeshort); memo1.lines.add(idHTTP1.response.ResponseText); except on e: EIdHTTPProtocolException do begin memo1.lines.add(idHTTP1.response.ResponseText); memo1.lines.add(e.ErrorMessage); end; end; memo1.Lines.add(html); makeshort.Free; end; 更新:我在这个例子中没有使用我的API密钥(通常应该没有一个可以正常运行)但是如果你想用自己的尝试,你可以用actionurl字符串代替 ParseError消息让我相信longurl在发布时可能会出现问题,但我不知道要改变什么. 我已经对此进行了一段时间的模糊测试,我确信错误就在眼前 – 我现在还没有看到它. 谢谢! 解决方法
正如您所发现的那样,TSdings重载版本的TIdHTTP.Post()方法是错误的使用方法.它发送application / x-www-form-urlencoded格式化请求,该请求不适用于JSON格式的请求.您必须使用Tdream重载版本的TIdHTTP.Post()方法,例如:
procedure TFrmMain.Button1Click(Sender: TObject); var html,actionurl: String; makeshort: TMemoryStream; begin try makeshort := TMemoryStream.Create; try actionurl := 'https://www.googleapis.com/urlshortener/v1/url'; WriteStringToStream(makeshort,'{"longUrl": "http://slashdot.org/stories"}',IndyUTF8Encoding); makeshort.Position := 0; IdHTTP1.Request.ContentType := 'application/json'; IdHTTP1.Request.Charset := 'utf-8'; html := IdHTTP1.Post(actionurl,makeshort); finally makeshort.Free; end; Memo1.Lines.Add(IdHTTP1.Response.ResponseText); Memo1.Lines.Add(html); except on e: Exception do begin Memo1.Lines.Add(e.Message); if e is EIdHTTPProtocolException then Memo1.lines.Add(EIdHTTPProtocolException(e).ErrorMessage); end; end; end; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |