簡體   English   中英

使用 Z4C4A218DB8E569D153ACC8A4533C4EDZ8 調用 REST Web API

[英]Calling REST Web API using Delphi

I have an ASP.NET MVC Web API and I need to call it using Delphi 6. I am trying to use the Indy components (version 9.0.18), I am using the TIdHttp component.

我正在使用 REST 方法,例如 POST 添加、PUT 更新和 DELETE 刪除記錄。 我成功添加、更新和獲取我的記錄,但我無法成功調用 DELETE 方法。 它會引發錯誤“HTTP/1.1 400 Bad Request”。

我試圖調試 Web API,但它似乎請求沒有到來,因為它沒有在斷點處停止。

我使用的 Indy 版本沒有 DELETE 方法,所以我嘗試使用 DoRequest 方法。

我的代碼:

IdHTTP.DoRequest(hmDelete, 'http://localhost/myapp/api/user/1', nil, nil);

如果我使用 Fiddler 發出請求,它可以工作,所以我的 Web API 運行良好。

作為 Indy 的替代方案,我建議您使用“項目”菜單中的“導入類型庫...”,然后選擇可用的最高版本“Microsoft XML”(我當前使用的機器上有 3 到 6 版) . 禁用“生成組件包裝器”,然后使用XMLHTTP組件進行 REST 調用。 例如:

uses ActiveX, MSXML2_TLB;

var
  r:XMLHTTP;
begin
  CoInitialize(nil);
  r:=CoXMLHTTP.Create;
  r.open('DELETE','http://localhost/myapp/api/user/1',false,'','');
  //r.setRequestHeader(...
  r.send(EmptyParam);
  if r.status=200 then

所以另一個答案很簡單,使用具有靈活后期綁定的 COM-Object,例如 REST 翻譯服務,在 GET 或 POST 中進行語言檢測,在 maXbox 腳本中實現:

function getPostTranslateLibre(feedstream: string): string;
var
  Url,API_KEY, source: string;
  jo, locate: TJSONObject;
  httpReq,hr: Olevariant;
  strm: TStringStream;
begin
   httpReq:= CreateOleObject('WinHttp.WinHttpRequest.5.1');
  // Open the HTTPs connection.  
 try              
  hr:= httpReq.Open('POST','https://libretranslate.pussthecat.org/detect', false);
   httpReq.setRequestheader('user-agent',
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0');
  httpReq.setRequestheader('content-type','application/x-www-form-urlencoded');  
//httpReq.setRequestheader('X-RapidAPI-Host','nlp-  translation.p.rapidapi.com');   
//httpReq.setRequestheader('X-RapidAPI-Key','...333'); 
          
if hr= S_OK then HttpReq.Send('q='+HTTPEncode(feedstream));
 /// Send HTTP Post Request & get Responses. 

If HttpReq.Status = 200 Then
   result:= HttpReq.responseText
Else result:= 'Failed at getting   response:'+itoa(HttpReq.Status)+HttpReq.responseText;
//writeln('debug response '+HttpReq.GetAllResponseHeaders);     
 finally
  httpreq:= unassigned;  
 end;                  
end; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM