开发环境:WIN10家庭版,Delphi XE4
功能需求:Delphi使用IdHTTP控件向web服务器发送一个请求,获得返回的数据。该服务器支持XML和JSON返回,说明中提到需要——“客户端指定ContentType="application/json",则服务器返回JSON格式”
请求语句:http://**.**.**.**:**/api/**/getlastinfo?tid=2123123&key=3546-2232-23421-2342

我使用Edge直接在浏览器中输入上述链接,返回正常:
{"tid":"2123123","Time":0,"Dir":240,"Mileage":0"Addr":{"Province":"山东省","City":"济南市"},}我使用DELPHI写入,代码如下:
url := 'http://**.**.**.**:**/api/**/getlastinfo?tid=2123123&key=3546-2232-23421-2342';
IdHTTP.Get(url, ts);     // ts 为TStringStream
ts.Position := 0;
ajson := SuperObject.so(ts.DataString);    // ajson为ISuperObject
dir := ajson['Dir'].AsInteger;     // 此句报错了
我把报错的语句注释掉,加上了Memo1.Lines.Add(ajson.AsString); 想看看返回的是否正确,结果Memo1显示的内容如下:
<TDetail xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/CloudMap.Models"><Time>0</Time><Dir>240</Dir><Addr><City>娴庡崡甯?/City><Province>灞变笢鐪?/Province></Addr></TDetail>
返回的应该不是JSON类型了,而且还是乱码,明明浏览器中测试通过,为什么不行能。是不是用IdHTTP发送请求错误?
在线等,谢谢!

解决方案 »

  1.   

    不是需求里说指定JSON格式吗?你加上去在看看结果。
      IdHTTP1.Request.ContentType := 'application/json';//设置内容类型为json
      

  2.   

    结果这样试试:(最好先showmessage(ts.DataString))看看结果是否正确
       jo:=SO(UTF8Decode(HttpDecode(ts.DataString)));
      dir:=jo['Dir'].Asinteger;
      

  3.   


    我这样设置了,返回数据还是:<TDetail xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/CloudMap.Models"><Time>0</Time><Dir>240</Dir><Addr><City>娴庡崡甯?/City><Province>灞变笢鐪?/Province></Addr></TDetail>
      

  4.   


    感谢,这个应该能消除乱码,但是还是不能使服务器返回JSON数据
      

  5.   

     初始化设置下
    idhtp1.HandleRedirects := true;
    idhtp1.Request.ContentType := 'application/x-www-form-urlencoded';
    idhtp1.Request.ContentEncoding := 'utf-8';
    idhtp1.ProtocolVersion := pv1_1;
      

  6.   

    先用postman测试接口,没问题了再处理程序。而且你收到的数据没有做任何检查,没有异常捕获。