POST
function HttpPost(sUrl, sJson: string): string;
varJsonToSend: TStringStream;idHttp1: TIdHTTP;
beginEnterCriticalSection(gPostCritDML);tryJsonToSend := TStringStream.Create(sJson, TEncoding.UTF8);Result := '';tryidHttp1 := TIdHTTP.Create(nil);idHttp1.HTTPOptions := [hoKeepOrigProtocol, hoForceEncodeParams];idHttp1.ConnectTimeout := 2000;idHttp1.Response.ContentType := 'application/json;charset=utf-8';idHttp1.Request.Accept := 'application/json;charset=utf-8';idHttp1.Request.ContentType := 'application/json;charset=utf-8';idHttp1.Request.CharSet := 'utf-8';tryResult := idHttp1.Post(sUrl, JsonToSend);excepton E: Exception dobeginSaveLogMsg('与后台服务通讯异常!' + e.Message);end;end;finallyFreeAndNil(JsonToSend);end;finallyidHttp1.Free;LeaveCriticalSection(gPostCritDML);end;
end;
sJson是JSON格式的字符串,例如:sJson := '{"factoryTag":"02","num":1}'
GET
function HttpGet(sUrl: string): string;
varidHttp1: TIdHTTP;
beginEnterCriticalSection(gGetCritDML);tryResult := '';idHttp1 := TIdHTTP.Create(nil);idHttp1.HTTPOptions := [hoKeepOrigProtocol, hoForceEncodeParams];idHttp1.ConnectTimeout := 2000;idHttp1.Response.ContentType := 'application/json;charset=utf-8';idHttp1.Request.Accept := 'application/json;charset=utf-8';idHttp1.Request.ContentType := 'application/json;charset=utf-8';idHttp1.Request.CharSet := 'utf-8';tryResult := idHttp1.Get(sUrl);excepton E: Exception dobeginSaveLogMsg(sUrl);SaveLogMsg('与后台服务通讯异常!' + e.Message);end;end;finallyidHttp1.Free;LeaveCriticalSection(gGetCritDML);end;
end;
JSON解析
导入System.JSON
function GetProduceId(cName: string; localComm: CLocalComm): string;
varsRsp, sJson: string;jRet: TJSONObject;
beginResult := '';sJson := '{"factoryTag":"02","num":1}';sRsp := HttpPost(ReadConfStr('url', 'sc_url') + 'productIdBd', sJson);if (sRsp <> '') and (Pos('{', sRsp) > 0) and (Pos('}', sRsp) > 0) thenbeginjRet := TJSONObject.ParseJSONValue(sRsp) as TJSONObject;if jRet.GetValue('code').Value = '0000' thenbeginend;end;
end;