星五博客

TNetHTTPCleint提交JSON串

这里,我们拿友盟的推送接口做个测试,它是要求同时提交get参数和post参数,post参数内容为json串,需要引用DateUtils和md5算法单元,代码如下:

procedure TForm1.Button3Click(Sender: TObject);
var
  vHttp: TNetHTTPClient;
  vS, vR: TStringStream;
  appkey, ams, timestamp, method, url, body, md5: string;
begin
  vHttp := TNetHTTPClient.Create(nil);
  vS := TStringStream.Create('', TEncoding.UTF8);
  vR := TStringStream.Create('', TEncoding.UTF8);
  try
    with vHttp do
    begin
      ConnectionTimeout := 2000; // 2秒
      ResponseTimeout := 10000; // 10秒
      AcceptCharSet := 'utf-8';
      AcceptEncoding := '65001';
      AcceptLanguage := 'zh-CN';
      ContentType := 'application/json';
      UserAgent := 'Embarcadero URI Client/1.0';
      appkey := '您的AppKey';
      ams := '您的App Master Secret';
      timestamp := FloatToStr(DateTimeToUnix(now, False));//返回unix时间戳
      method := 'POST';
      url := 'http://msg.umeng.com/api/send';
      body := '{"appkey":"' + appkey + '",'
        + '"timestamp":"' + timestamp + '",'
        + '"type":"customizedcast",'
      // +'"device_tokens":"",'
        + '"alias_type": "别名类型",'
        + '"alias":"别名1,别名2",'
        + '"payload":{"aps":{"alert": "您好!祝您生活愉快!'
        + '","badge":1,"sound":"default"}},'
        + '"description": "测试"}';
      vS.WriteString(method + url + body + ams);//友盟要求的签名算法
      md5 := LowerCase(MD5Print(MD5Stream(vS)));//签名要用md5输出,小写32位
      vS.Clear;
      vS.WriteString(body);
      vS.Position := 0;
      try
        Post(url + '?sign=' + md5, vS, vR);//拼接url并进行post提交
        Memo1.Lines.Add('post:' + vR.DataString);
      except
        on E: Exception do
          // Error sending data: (12002) 操作超时.
          // Error receiving data: (12002) 操作超时
          if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
          then
            Memo1.Lines.Add('post:连接失败!')
          else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
          then
            Memo1.Lines.Add('post:接收失败,请延长接收超时时间!')
          else
            Memo1.Lines.Add('post:' + E.Message);
      end;
    end;
  finally
    vS.Free;
    vR.Free;
    vHttp.Free;
  end;
end;

其实就是按流的形式进行提交就可以了,和拼接xml去post请求soap接口是一个道理。

Delphi