首页 > 解决方案 > 如何使用 Delphi 的 Google 安全浏览 API v4

问题描述

我无法使用谷歌安全浏览 api v4。我确信这应该很容易,但它已经花费了我一些时间。我总是收到错误400 bad request。这是我的代码:

var
  idHttp : TIdHTTPEx;
  url : string;
  slTemp : TStringList;
  memoryStream : TMemoryStream;
begin
  idHttp := TIdHTTPEx.Create(nil); // parent class is TIdHTTP, inherited to be able to execute HTTPS
  slTemp := TStringList.Create;
  memoryStream := TStringStream.Create;
  try
    idHttp.Request.ContentType := 'application/json';

    url := 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' + GOOGLE_SAFE_BROWSING_API_KEY + ' HTTP/1.1';
    slTemp.Text := '{"client":{"clientId":"iGame","clientVersion":"1.0.0"},"threatInfo":{"threatTypes":"MALWARE","platformTypes":"WINDOWS","threatEntryTypes":"URL","threatEntries":[{"url":"http://www.hyxyg.com/default.php"},{"url":"https://jsonlint.com/"}]}}';

    idHttp.Post(url, slTemp, memoryStream);
    memo1.Text := memoryStream.ToString;

  finally
    memoryStream.Free;
    slTemp.Free;
    idHttp.Free;
  end;
end;

我试过检查这个,但它使用的是较低版本。我哪里做错了?

编辑

我尝试按照其中一条评论的建议使用,但仍然是相同的错误400 bad request。这个例子还可以。

var
  idHttp : TIdHTTPEx; // parent class is TIdHTTP, inherited to be able to execute HTTPS
  url : string;
  requestBody : TStream;
  sTemp : string;
begin
  url := 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' + GOOGLE_SAFE_BROWSING_API_KEY + ' HTTP/1.1';
  //url := 'https://httpbin.org/post';

  idHttp := TIdHTTPEx.Create(nil);
  requestBody := nil;
  try

    idHttp.Request.Accept := 'application/json';
    idHttp.Request.ContentType := 'application/json';

    sTemp := '{"client":{"clientId":"iGame","clientVersion":"1.0.0"},"threatInfo":{"threatTypes":"MALWARE","platformTypes":"WINDOWS","threatEntryTypes":"URL","threatEntries":[{"url":"http://www.hyxyg.com/default.php"},{"url":"https://jsonlint.com/"}]}}';
    //sTemp := '{"日本語":42}';

    requestBody := TStringStream.Create(sTemp, TEncoding.UTF8);
    sTemp := idHttp.Post(url, requestBody);

    memo1.Text := sTemp + sLineBreak + sLineBreak + idHttp.ResponseText;

  finally
    requestBody.Free;
    idHttp.Free;
  end;
end;

标签: delphi

解决方案


URI 末尾的“HTTP/1.1”一定是错误,不带它试试。


推荐阅读