分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

idHttp 中GET POST应用

发布时间:2023-09-06 01:25责任编辑:胡小海关键词:GETPOST

转:https://www.cnblogs.com/limingliyu/archive/2016/07

使用IDHTTP,下面是一些关于 GET、POST 请求基本使用方法的代码

一、GET 请求

 1 procedure GetDemo; 2 var 3 ??IdHttp : TIdHTTP; 4 ??Url : string;//请求地址 5 ??ResponseStream : TStringStream; //返回信息 6 ??ResponseStr : string; 7 begin 8 ??//创建IDHTTP控件 9 ??IdHttp := TIdHTTP.Create(nil);10 ??//TStringStream对象用于保存响应信息11 ??ResponseStream := TStringStream.Create(‘‘);12 ??try13 ????//请求地址14 ????Url := ‘http://dict.youdao.com/‘;15 ????try16 ??????IdHttp.Get(Url,ResponseStream);17 ????except18 ??????on e : Exception do19 ??????begin20 ????????ShowMessage(e.Message);21 ??????end;22 ????end;23 ????//获取网页返回的信息24 ????ResponseStr := ResponseStream.DataString;25 ????//网页中的存在中文时,需要进行UTF8解码26 ????ResponseStr := UTF8Decode(ResponseStr);27 ??finally28 ????IdHttp.Free;29 ????ResponseStream.Free;30 ??end; ??31 end;

如果Get需要添加请求参数,则直接在地址后添加,各参数间用&连接

如:http://dict.youdao.com?param1=1&param2=2

二、Post 请求

 1 procedure PostDemo; 2 var 3 ??IdHttp : TIdHTTP; 4 ??Url : string;//请求地址 5 ??ResponseStream : TStringStream; //返回信息 6 ??ResponseStr : string; 7 ?8 ??RequestList : TStringList; ????//请求信息 9 ??RequestStream : TStringStream;10 begin11 ??//创建IDHTTP控件12 ??IdHttp := TIdHTTP.Create(nil);13 ??//TStringStream对象用于保存响应信息14 ??ResponseStream := TStringStream.Create(‘‘);15 16 ??RequestStream := TStringStream.Create(‘‘);17 ??RequestList := TStringList.Create;18 ??try19 ????Url := ‘http://f.youdao.com/?path=fanyi&vendor=fanyiinput‘;20 ????try21 ??????//以列表的方式提交参数22 ??????RequestList.Add(‘text=love‘);23 ??????IdHttp.Post(Url,RequestList,ResponseStream);24 25 ??????//以流的方式提交参数26 ??????RequestStream.WriteString(‘text=love‘);27 ??????IdHttp.Post(Url,RequestStream,ResponseStream);28 ????except29 ??????on e : Exception do30 ??????begin31 ????????ShowMessage(e.Message);32 ??????end;33 ????end;34 ????//获取网页返回的信息35 ????ResponseStr := ResponseStream.DataString;36 ????//网页中的存在中文时,需要进行UTF8解码37 ????ResponseStr := UTF8Decode(ResponseStr);38 ??finally39 ????IdHttp.Free;40 ????RequestList.Free;41 ????RequestStream.Free;42 ????ResponseStream.Free;43 ??end;44 end;

Post请求在网页中多使用List形式提交参数。

不过在一些API中规定了POST的请求格式为 JSON 格式或 XML,这是需要注意发起请求前需要先设置 ContentType 属性,使用Stream方式提交

已上面代码为例:

提交 JSON 格式:IdHttp.Request.ContentType :=‘application/json‘;

提交 XML 格式: IdHttp.Request.ContentType :=‘text/xml‘;

如未按要求格式提交,一般会返回 HTTP 1.1 / 415

/03/5638966.html

idHttp 中GET POST应用

原文地址:http://www.cnblogs.com/maweiwei/p/7865445.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved