温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Delphi中怎么调用WebApi

发布时间:2021-06-24 16:00:48 来源:亿速云 阅读:1516 作者:Leah 栏目:大数据

Delphi中怎么调用WebApi,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Delphi调用WebApi时我们用到了IXMLHttpRequest,在单元引用里面加上msxml即可.

调用起来非常简单,定义HttpReq: IXMLHttpRequest;

    HttpReq := CoXMLHTTPRequest.Create;

    HttpReq.open('Post', url, False, EmptyParam, EmptyParam);
    上面的参数第一个就是用到的方法GET就写'Get',Post就写'Post',第二个是通讯地址,后面的就默认这样填写就到了   

    HttpReq.setRequestHeader('Accept', 'application/json');
    HttpReq.setRequestHeader('Content-Type', 'application/json');

    上面是设置请求头的格式


    HttpReq.send(parasjson); //开始搜索
    在Send里面,如果用的GET方法就直接填入EmptyParam,如果用的POST方法就在这里填入自己的JSON字符串

    resultjson := HttpReq.responseText;

    获取返回信息

GET方法必须注意一点

Delphi中怎么调用WebApi

delphi用IXMLHttpRequest的GET方法时必须加上时间戳   '&timestamp='+inttostr(Windows.GetTickCount),如果后面不加上时间戳,只会GET一次,不再请求GET了

自己封装的完整调用WebApi的单元

unit DoWebApi;

interface

uses
  Variants, msxml, SysUtils, Windows;

  //WebApi
  //GET
function WebApiGet(url : string; var resultjson: string; parasstr:string=''): Integer;
  //Post
function WebApiPost(url, parasjson: string; var resultjson: string): Integer;


implementation


//获取Get
//delphi用IXMLHttpRequest的GET方法时必须加上时间戳   '&timestamp='+inttostr(Windows.GetTickCount)
//如果不加只会GET一次,不再GET了
// Added by Administrator 2016-09-23 16:17:08
function WebApiGet(url: string; var resultjson: string;parasstr:string=''): Integer;
var
  transurl: string;
  HttpReq: IXMLHttpRequest;
begin
  if parasstr = '' then
    transurl := url + '?timestamp=' + inttostr(Windows.GetTickCount)
  else
    transurl := url + '?' + parasstr + '&timestamp=' + inttostr(Windows.GetTickCount);
  Result := -1;
  try
    try
      HttpReq := CoXMLHTTPRequest.Create;
      HttpReq.open('get', transurl, False, EmptyParam, EmptyParam);

      HttpReq.setRequestHeader('Accept', 'application/json');
      HttpReq.setRequestHeader('Content-Type', 'application/json');

      HttpReq.send(EmptyParam); //开始搜索

      resultjson := HttpReq.responseText;
      Result := 0;
    except
      Result := -1;
    end;
  finally

  end;

end;

//Post
function WebApiPost(url, parasjson: string; var resultjson: string): Integer;
var
  HttpReq: IXMLHttpRequest;
begin
  Result := -1;
  try
    HttpReq := CoXMLHTTPRequest.Create;
    HttpReq.open('Post', url, False, EmptyParam, EmptyParam);

    HttpReq.setRequestHeader('Accept', 'application/json');
    HttpReq.setRequestHeader('Content-Type', 'application/json');

    HttpReq.send(parasjson); //开始搜索

    resultjson := HttpReq.responseText;
    Result := 0;
  except
    Result := -1;
  end;
end;
end.

关于Delphi中怎么调用WebApi问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI