Delphi HTTP Post JSON [英] Delphi HTTP Post JSON

查看:305
本文介绍了Delphi HTTP Post JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我在这里做错事。我已经遵循了我可以在stackoverflow上找到的每一个例子,但仍然没有在我的环境中工作。我很乐意更新我的控件和环境,但是我目前正在锁定我的内容。



我正在使用:




  • Delphi 7

  • Indy 10.0.52

  • ulkJSON.pas v1.07



我需要将此JSON发送到一个URL:

 auth:{
applicationId :appID,
applicationPassword:pwd,
accountId:acct,
userId:dev
}

没有什么可怕的疯狂,但是当我尝试发布我的请求时,我会收到一条消息请求被正常关闭。 CheckIs可以在IDSocketHandle.pas中具有Handleallocated = false。我不知道我在配置我的IdHTTP时做错了什么,但是它不会工作。



我已经尝试过所有这些问题的例子,还有几个,但是这些方法似乎都不适用于我:





任何提示将不胜感激。 >

当前的变体如下所示:

 程序Tformmaintestbed.btnJSONSendClick(发件人: TObject); 
var
code:Integer;
sResponse:string;
JsonToSend:TStringStream;
begin
JsonToSend:= TStringStream.Create(
'{auth:{applicationId:'+ edApplication.text +
',applicationPassword '+ edpassword.text +
',accountId:'+ edaccount.text +
',userId:'+ edUser.text +
'}} ');
try
HTTP1.Request.ContentType:='application / json';
HTTP1.Request.ContentEncoding:='utf-8';

memoRequest.lines.clear;
memoRequest.lines.add(JsonToSend);

try
sResponse:= HTTP1.Post(cbAddress.text,JsonToSend);
除了
在E:Exception do
ShowMessage('Error on request:'#13#10 + e.Message);
结束

memoResponse.lines.clear;
memoresponse.lines.add(sResponse);
finally
JsonToSend.Free();
结束
结束

idHTTP组件是这样设置的:

 对象HTTP1:TIdHTTP 
IOHandler = IdSSLIOHandlerSocketOpenSSL1
AuthRetries = 0
AuthProxyRetries = 0
AllowCookies = True
HandleRedirects = True
ProxyParams.BasicAuthentication = False
ProxyParams.ProxyPort = 0
Request.ContentEncoding ='utf-8'
Request.ContentLength = -1
Request.ContentRangeEnd = 0
Request.ContentRangeStart = 0
Request.ContentRangeInstanceLength = 0
Request.ContentType ='application / json'
Request.Accept ='application / json'
请求.BasicAuthentication = False
Request.UserAgent ='Mozilla / 3.0(兼容; Indy库)'
HTTPOptions = [hoForceEncodeParams]
左= 564
顶= 120
结束


解决方案

HTTP1.Request。 ContentEncoding 应该是 HTTP1.Req uest.CharSet 代替。 UTF-8是一种字符集编码,而不是内容编码。然后在发布之前确保您的JSON数据实际上被编码为UTF-8。如果您使用ASCII字符,您显示的 TStringStream 代码是正确的。但是,如果您使用非ASCII字符,则需要对它们进行编码,例如使用 Utf8Encode() TIdHTTP 不编码 TStream 数据,它是按原样发送的。

 过程Tformmaintestbed.btnJSONSendClick(Sender:TObject); 
var
Json:string;
sResponse:string;
JsonToSend:TStringStream;
begin
Json:='{auth:{applicationId:'+ edApplication.text +
',applicationPassword:'+ edpassword.text +
',accountId:'+ edaccount.text +
',userId:'+ edUser.text +
'}}';

memoRequest.Text:= Json;

JsonToSend:= TStringStream.Create(Utf8Encode(Json)); // D2007和更早版本只有
//在D2009及更高版本中,使用它代替:
// JsonToSend:= TStringStream.Create(Json,TEncoding.UTF8);
try
HTTP1.Request.ContentType:='application / json';
HTTP1.Request.CharSet:='utf-8';

try
sResponse:= HTTP1.Post(cbAddress.Text,JsonToSend);
除了
在E:Exception do
ShowMessage('Error on request:'#13#10 + e.Message);
结束
finally
JsonToSend.Free;
结束

memoResponse.Text:= sResponse;
结束

或者:

 code>过程Tformmaintestbed.btnJSONSendClick(Sender:TObject); 
var
Json:string;
sResponse:string;
JsonToSend:TMemoryStream;
begin
Json:='{auth:{applicationId:'+ edApplication.text +
',applicationPassword:'+ edpassword.text +
',accountId:'+ edaccount.text +
',userId:'+ edUser.text +
'}}';

memoRequest.Text:= Json;

JsonToSend:= TMemoryStream.Create;
try
WriteStringToStream(JsonToSend,Json,enUTF8);
JsonToSend.Position:= 0;

HTTP1.Request.ContentType:='application / json';
HTTP1.Request.CharSet:='utf-8';

try
sResponse:= HTTP1.Post(cbAddress.Text,JsonToSend);
除了
在E:Exception do
ShowMessage('Error on request:'#13#10 + e.Message);
结束
finally
JsonToSend.Free;
结束

memoResponse.Text:= sResponse;
结束


I am sure I'm doing something wrong here. I've followed every example I can find on stackoverflow and still haven't gotten this to work in my environment. I'd love to update my controls and environment, but I'm currently locked in with what I have.

I am using:

  • Delphi 7
  • Indy 10.0.52
  • ulkJSON.pas v1.07

I need to send this JSON to a URL:

"auth": {
    "applicationId": "appID",
    "applicationPassword": "pwd",
    "accountId": "acct",
    "userId": "dev"
}

There isn't anything terribly crazy about this, but when I try to post my request I tend to get a message that the request was Closed Gracefully. CheckIsReadable in IDSocketHandle.pas has Handleallocated = false. I'm not sure what I've done wrong in configuring my IdHTTP, but it just won't work.

I have tried examples from all these questions and several more, but none of these approaches seem to work for me:

Any tips would be greatly appreciated.

The current variant looks like this:

procedure Tformmaintestbed.btnJSONSendClick(Sender: TObject);
var
  code: Integer;
  sResponse: string;
  JsonToSend: TStringStream;
begin
  JsonToSend := TStringStream.Create(
    '{"auth": {"applicationId": "' + edApplication.text +
    '","applicationPassword": "' + edpassword.text +
    '","accountId": "' + edaccount.text +
    '","userId": "' + edUser.text +
    '"}}');
  try
    HTTP1.Request.ContentType := 'application/json';
    HTTP1.Request.ContentEncoding := 'utf-8';

    memoRequest.lines.clear;
    memoRequest.lines.add(JsonToSend);

    try
      sResponse := HTTP1.Post(cbAddress.text, JsonToSend);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;

    memoResponse.lines.clear;
    memoresponse.lines.add(sResponse);
  finally
    JsonToSend.Free();
  end;
end;

The idHTTP component is current set like this:

object HTTP1: TIdHTTP
  IOHandler = IdSSLIOHandlerSocketOpenSSL1
  AuthRetries = 0
  AuthProxyRetries = 0
  AllowCookies = True
  HandleRedirects = True
  ProxyParams.BasicAuthentication = False
  ProxyParams.ProxyPort = 0
  Request.ContentEncoding = 'utf-8'
  Request.ContentLength = -1
  Request.ContentRangeEnd = 0
  Request.ContentRangeStart = 0
  Request.ContentRangeInstanceLength = 0
  Request.ContentType = 'application/json'
  Request.Accept = 'application/json'
  Request.BasicAuthentication = False
  Request.UserAgent = 'Mozilla/3.0 (compatible; Indy Library)'
  HTTPOptions = [hoForceEncodeParams]
  Left = 564
  Top = 120
end

解决方案

HTTP1.Request.ContentEncoding should be HTTP1.Request.CharSet instead. UTF-8 is a charset encoding, not a content encoding. And then make sure your JSON data is actually encoded to UTF-8 before posting it. If you are using ASCII characters, the TStringStream code you showed is fine. But if you are using non-ASCII Characters, you need to encode them, such as with Utf8Encode(). TIdHTTP does not encode TStream data, it is sent as-is.

Procedure Tformmaintestbed.btnJSONSendClick(Sender: TObject);
var
  Json: string;
  sResponse: string;
  JsonToSend: TStringStream;
begin
  Json := '{"auth": {"applicationId": "' + edApplication.text +
    '","applicationPassword": "' + edpassword.text +
    '","accountId": "' + edaccount.text +
    '","userId": "' + edUser.text +
    '"}}';

  memoRequest.Text := Json;

  JsonToSend := TStringStream.Create(Utf8Encode(Json)); // D2007 and earlier only
  //in D2009 and later, use this instead:
  //JsonToSend := TStringStream.Create(Json, TEncoding.UTF8);
  try
    HTTP1.Request.ContentType := 'application/json';
    HTTP1.Request.CharSet := 'utf-8';

    try
      sResponse := HTTP1.Post(cbAddress.Text, JsonToSend);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    JsonToSend.Free;
  end;

  memoResponse.Text := sResponse;
end;

Alternatively:

Procedure Tformmaintestbed.btnJSONSendClick(Sender: TObject);
var
  Json: string;
  sResponse: string;
  JsonToSend: TMemoryStream;
begin
  Json := '{"auth": {"applicationId": "' + edApplication.text +
    '","applicationPassword": "' + edpassword.text +
    '","accountId": "' + edaccount.text +
    '","userId": "' + edUser.text +
    '"}}';

  memoRequest.Text := Json;

  JsonToSend := TMemoryStream.Create;
  try
    WriteStringToStream(JsonToSend, Json, enUTF8);
    JsonToSend.Position := 0;

    HTTP1.Request.ContentType := 'application/json';
    HTTP1.Request.CharSet := 'utf-8';

    try
      sResponse := HTTP1.Post(cbAddress.Text, JsonToSend);
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    JsonToSend.Free;
  end;

  memoResponse.Text := sResponse;
end;

这篇关于Delphi HTTP Post JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆