idHttp 两种传输数据的方法,即get 和 post 总结
*服务端用c# 模拟 WebApi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace webapitest1.Controllers
{
public class ProductController : ApiController
{
public string Get()
{
return "调用Get 无参方法";
}
[HttpGet]
public string Get([FromUri]string msg) {
return $"调用Get有参方法:{msg}";
}
[HttpPost]
public string Post(dynamic obj) {
return $"调用post方法,传入参数:{obj.name},{obj.age}";
}
}
}
- 客户端用Delphi 测试(Delphi中默认的字符编码为Ansi,而网络中基本上使用的都是utf8,因此注意转码)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdHTTP, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
IdHTTP1: TIdHTTP;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
url:string;
responsestream:TStringStream;
ResponseStr:string;
requestList:TStringList;
RequestStream:TStringStream;
jsonStr:string;
begin
responsestream:=TStringStream.Create('');
RequestStream:=TStringStream.Create('');
requestList:=TStringList.Create;
url:='http://localhost:55867/api/product';
requestList.Add('name=张三');
requestList.Add('age=22');
try
//IdHTTP1.Post(url,requestList,responsestream); //列表方式提交
//responsestream.Position:=0;
RequestStream.WriteString(AnsiToUtf8('{"name":"张三","age":22}'));//这里用转码是为了传输带有中文的参数
IdHTTP1.Request.ContentType:='application/json'; //指定传输类型为json,主要为了方便服务端dynamic 动态推断类型,即可以把json字符串自动转换成object 对象
IdHTTP1.Post(url,RequestStream,responsestream); //流方式提交
responsestream.Position:=0;
Memo1.Lines.Add(StringReplace(Utf8ToAnsi(responsestream.DataString),'"','',[rfReplaceAll])); //这里去除了双引号 "
responsestream.Free;
RequestStream.Free;
requestList.Free;
except on e:Exception do
begin
ShowMessage(e.Message);
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
stream:TStringStream;
url:string;
begin
url:='http://localhost:55867/api/product';
try
stream:=TStringStream.Create('');
IdHTTP1.Get(url,stream);
stream.Position:=0;
Memo1.Lines.Add(Utf8ToAnsi(stream.DataString));
finally
stream.Free;
end;
end;
end.
标签:end,string,get,url,idhttp,requestList,using,post,responsestream
From: https://www.cnblogs.com/sundh1981/p/17583220.html