简体   繁体   中英

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.

I am using the REST methods, like POST to add, PUT to update and DELETE to delete the records. I got successfully adding, updating and getting my records, but I couldn't get successfully to call the DELETE method. It raises an error "HTTP/1.1 400 Bad Request".

I tried to debug the Web API, but it appers that the request didn't come, cause it doesn't stop in the breakpoint.

The Indy version that I am using doesn't have the method DELETE, so I tried to use the DoRequest method.

My code:

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

If I make the request using Fiddler it works, so my Web API is working well.

As an alternative to Indy, I suggest you use "Import Type Library..." from the Project menu, and select "Microsoft XML", the highest version available (I have versions 3 through 6 on the machine I'm currently on). Disable "Generate Component Wrapper", and then use the XMLHTTP component to make REST calls. Eg:

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

So another answer is simple, use a COM-Object with flexible late binding, example of a REST translate service with language detection in GET or POST, implements in maXbox script:

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM