Ali*_*adi 0 delphi json idhttp delphi-xe
我曾经遇到过一个使用了几个网站JSON的请求和响应
我遇到两种类型:
1 application/x-www-form-urlencoded请求和返回响应application/json内容类型
2- application/json内容类型请求和响应
在type 1我试图用改变的响应内容类型
mIdHttp.Response.ContentType := 'application/json';
,但使用HTTP分析器,我可以看到它没有改变,它text/html
现在仍然不知道问题是否与我无法改变内容类型的事实,但我不知道如何处理json!
关于json以下问题:
1-我必须在发布时对json数据进行编码吗?怎么样 ?
2-我如何解析json响应代码?怎么弄明白?它需要某种编码或特殊转换吗?
3- json的哪种idhttp设置随每个站点的变化而需要配置?
我理解我的问题听起来有点笼统,但所有其他问题都非常具体,并且在处理'application/json'内容类型时没有解释基本知识.
编辑1:
感谢Remy Lebeau 回答我能够成功合作,type 1
但我仍然无法发送JSON请求,有人可以分享一个工作示例,这是发布信息的网站之一,请使用此示例:
一个重要的注意事项: 这个特定网站的帖子和请求内容完全相同!因为在现场,我指定它令我感到困惑start date和end date然后点击一个folder like icon,这post被发送(一个你可以在上面看到),而result应该是links(它是),而不是只出现在request content它们也会出现在post!(我也试图获取链接,但在post链接,我想要的东西,也被发送,我怎么能发布我没有的东西!!?)
您不能指定响应的格式,除非请求的资源为此确切目的提供显式输入参数或专用URL(即,请求将响应作为html,xml,json等发送).设置TIdHTTP.Response.ContentType属性是没用的.它将被Content-Type响应的实际标头覆盖.
要在请求中发送 JSON,您必须将其发布为a TStream,like TMemoryStream或TStringStream,并TIdHTTP.Request.ContentType根据需要进行设置,例如:
var
ReqJson: TStringStream;
begin
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Post(URL, ReqJson);
finally
ReqJson.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
要接收 JSON,TIdHTTP也可以
将其作为a String(使用服务器报告的字符集解码)返回:
var
ReqJson: TStringStream;
RespJson: String;
begin
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
RespJson := IdHTTP1.Post(URL, ReqJson);
finally
ReqJson.Free;
end;
// use RespJson as needed...
end;
Run Code Online (Sandbox Code Playgroud)将原始字节写入TStream您选择的输出:
var
ReqJson: TStringStream;
RespJson: TMemoryStream;
begin
RespJson := TMemoryStream.Create;
try
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
RespJson := IdHTTP1.Post(URL, ReqJson, RespJson);
finally
ReqJson.Free;
end;
RespJson.Position := 0;
// use RespJson as needed...
finally
RespJson.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)HTTP响应代码在TIdHTTP.Response.ResponseCode(和TIdHTTP.ResponseCode)属性中可用.
| 归档时间: |
|
| 查看次数: |
8740 次 |
| 最近记录: |