gpt4 book ai didi

Delphi:使用 Google URL Shortener 和 IdHTTP - 400 错误请求

转载 作者:行者123 更新时间:2023-12-03 15:25:49 24 4
gpt4 key购买 nike

我正在尝试从 Delphi 中通过其 API 访问 URL 缩短器 ( http://goo.gl/ )。但是,我得到的唯一结果是:HTTP/1.0 400 Bad Request (reason: parseError)

这是我的代码(在带有 Button1Memo1IdHTTP1 的表单上,其中 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 key (通常在没有 key 的情况下尝试几次也能正常工作),但如果您想用自己的 API key 进行尝试,则可以将其替换为actionurl 字符串 'https://www.googleapis.com/urlshortener/v1/url?key=<yourapikey>';

ParseError 消息让我相信长网址的编码在发布时可能有问题,但我不知道要更改什么。

我已经对此模糊了很长一段时间,我确信这个错误就在我眼前 - 我只是现在没有看到它。因此,非常感谢任何帮助!

谢谢!

最佳答案

正如您所发现的,TStrings 重载版本的 TIdHTTP.Post() 方法是错误的使用方法。它发送 application/x-www-form-urlencoded 格式的请求,这不适用于 JSON 格式的请求。您必须改用 TStream 重载版本的 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;

关于Delphi:使用 Google URL Shortener 和 IdHTTP - 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com