https和http的post发送总结
需要转发数据到客户的https的服务器上出现一系列问题总结如下:
1.因为是https首先考虑到用最新的控件NetHTTPClient(只有在XE8以上才有)。
2.客户的服务器需要先登录
例如:域名/authentication?account=admin&password=001
Method: POST
return:
200:成功
404:不存在
606:自定义错误
3.登录成功后需要向下面地址提交json数据
URL:
域名/measVals/batch
Method:
POST
4.代码
var
Jsonstr:ansistring;
Url,ResData:string;
ResponseStream:TStringStream;
resStr:integer;
HTTPRespone:IHTTPResponse;//THTTPResponse;
ss : TMemoryStream;
begin
NetHTTPClient1.AllowCookies:=true;
with NetHTTPClient1 do
begin
//AcceptCharSet := 'utf-8';
ConnectionTimeout := 2000; // 2秒
ResponseTimeout := 10000; // 10秒
AcceptEncoding := 'UTF-8';
AcceptEncoding := '65001';
AcceptLanguage := 'zh-CN';
ContentType := 'application/json; charset=utf-8';//'multipart/form-data';//'application/json';
// UserAgent := 'Embarcadero URI Client/1.0';
//UserAgent := 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)';//'Embarcadero URI Client/1.0';
end;
ResponseStream := TStringStream.Create;
ss := TMemoryStream.Create();
//登录
Url:='https://域名.com/platform/authentication?account=admin&password=001';
HTTPRespone:=NetHTTPClient1.Post(Url,ss,ResponseStream);
memo1.Lines.Add(ResponseStream.DataString);
//提交数据
Url:='https://域名.com/platform/measVals/batch';
Jsonstr:='{"tourId":"0","st":"MOBILE","mu":[{"num":"12345678","man":"test",'+
'"med":"07", "ver":"0","measCur":[ { "time":"1555050716", "volume": { "unit":"m",'+
'"value":"13" } }] }] }';
ss.Write(Jsonstr[1], Length(Jsonstr));
ss.Position := 0;
resStr:=NetHTTPClient1.Post(Url,ss,ResponseStream).StatusCode;
memo1.Lines.Add(ResponseStream.DataString);
end;
5.需要注意的问题
(1)因为本例中登录后需要记录session,开始测试用的dXE10.1,始终记录不了session,后来查了网络知道是该版本的bug,后来换用最新的XE10.3才可以NetHTTPClient1.AllowCookies:=true;
(2)提交json数据开始用TStringStream向对方提交数据,对方始终收到的是空,后来改用TMemoryStream才可以收到,并且json数据要用Jsonstr:ansistring; 否则对方收到的长度只有一半。