IdHttp:如何处理json请求和响应

时间:2016-08-20 17:17:51

标签: json delphi delphi-xe idhttp

我遇到过一些使用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请求,有人可以分享一个工作示例,这是发布信息的网站之一,请以此为例: enter image description here

一个重要说明:此特定网站的帖子和请求内容完全相同!并且它让我感到困惑,因为在网站上,我指定了start dateend date,然后点击folder like icon并发送此post(您可以在上面看到的那个) ,result应该是links(而且是)而不是只出现在request content中,它们也出现在post中! (我也试图获取链接,但在post链接,我想要的东西,也被发送,我怎么能发布我不会发的东西!!?)< / p>

只是为了更清晰这里是我填写日期和我提到的图标的地方:
enter image description here

1 个答案:

答案 0 :(得分:7)

您不能指定响应的格式,除非请求的资源为此确切目的提供显式输入参数或专用URL(即,请求将响应发送为html,xml,json等)。设置TIdHTTP.Response.ContentType属性是没用的。它将被响应的实际Content-Type标头覆盖。

要在请求中发送 JSON,您必须将其作为TStream发布,例如TMemoryStreamTStringStream,并设置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;

接收 JSON,TIdHTTP可以

  1. 将其作为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;
    
  2. 将原始字节写入您选择的输出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;
    
  3. HTTP响应代码位于TIdHTTP.Response.ResponseCode(和TIdHTTP.ResponseCode)属性中。

相关问题