[英]HTTP POST with Wininet API on Delphi
I'm using Delphi 2010 for sending an HTTP request to a Java application. 我正在使用Delphi 2010向Java应用程序发送HTTP请求。 Specifically, I'm sending a JSON object.
具体来说,我正在发送一个JSON对象。 But, when sending the request, I don't know what's happening, but the object is not correct.
但是,在发送请求时,我不知道发生了什么,但对象不正确。
I send the object like this: 我像这样发送对象:
{"entidad":"1","username":"A","password":"1234"}
My sniffer reads the object like this: 我的嗅探器读取这样的对象:
%�7�B�%�2�2�e�n�t�i�d�a�d�%�2�2�%�3�A�%�2�2�8�3�0�0�2�3�0�0�0�%�2�2�%�2�C�
Therefore, my Java application doesn't read the object and it's causing a null pointer exception. 因此,我的Java应用程序不会读取该对象,而是导致空指针异常。
My code is here: 我的代码在这里:
function TFormMain.JSONPostRequest(Server,Url,jo : String; blnSSL: Boolean): String;
var
aBuffer : Array[0..4096] of Char;
Header : TStringStream;
BufStream : TMemoryStream;
BytesRead : Cardinal;
pSession : HINTERNET;
pConnection : HINTERNET;
pRequest : HINTERNET;
port : Integer;
flags : DWord;
begin
Result := '';
pSession := InternetOpen(nil, INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(pSession) then
try
if blnSSL then
Port := INTERNET_DEFAULT_HTTPS_PORT
else
Port := 9000;
pConnection := InternetConnect(pSession, PChar(Server), port, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
if Assigned(pConnection) then
try
if blnSSL then
flags := INTERNET_FLAG_SECURE or INTERNET_FLAG_KEEP_CONNECTION
else
flags := INTERNET_SERVICE_HTTP;
pRequest := HTTPOpenRequest(pConnection, 'POST', PChar(Url), nil, nil, nil, flags, 0);
if Assigned(pRequest) then
try
Header := TStringStream.Create('');
try
with Header do
begin
WriteString('Host: ' + Server + ':' + IntToStr(Port) + sLineBreak);
end;
HttpAddRequestHeaders(pRequest, PChar(Header.DataString), Length(Header.DataString), HTTP_ADDREQ_FLAG_ADD);
if HTTPSendRequest(pRequest, nil, 0, Pointer(jo), Length(jo)) then
begin
BufStream := TMemoryStream.Create;
try
while InternetReadFile(pRequest, @aBuffer, SizeOf(aBuffer), BytesRead) do
begin
if (BytesRead = 0) then Break;
BufStream.Write(aBuffer, BytesRead);
end;
aBuffer[0] := #0;
BufStream.Write(aBuffer, 1);
Result := WideCharToString(PChar(BufStream.Memory));
finally
BufStream.Free;
end;
end
else
raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
finally
Header.Free;
end;
finally
InternetCloseHandle(pRequest);
end;
finally
InternetCloseHandle(pConnection);
end;
finally
InternetCloseHandle(pSession);
end;
end;
JSON uses UTF-8 by default, Delphi (2009 and newer) uses UTF-16 as default encoding. JSON默认使用UTF-8,Delphi(2009及更新版本)使用UTF-16作为默认编码。 Your code needs to convert the JSON to a UTF-8 string before passing it to HTTPSendRequest.
您的代码需要在将JSON传递给HTTPSendRequest之前将其转换为UTF-8字符串。
I would also add a request header to indicate the encoding, so that the Java side knows that it is UTF-8. 我还会添加一个请求标头来指示编码,以便Java端知道它是UTF-8。
My sniffer reads the object like this:
我的嗅探器读取这样的对象:
% 7 B % 2 2 e n t i d a d % 2 2 % 3 A % 2 2 8 3 0 0 2 3 0 0 0 % 2 2 % 2 C
Your JSON data is encoded in UTF-16, because string
is an alias for UnicodeString
in Delphi 2010. You are sending the raw bytes of that string as-is instead of encoding them to UTF-8, which is JSON's default charset. 您的JSON数据以UTF-16编码,因为
string
是Delphi 2010中UnicodeString
的别名。您正在发送该字符串的原始字节,而不是将它们编码为UTF-8,这是JSON的默认字符集。 As mjn said, you are misusing HttpSendRequest()
in that regard. 正如mjn所说,你在这方面滥用
HttpSendRequest()
。
Also, your input JSON string appears to have been url-encoded before being passed to JSONPostRequest()
( HTTPSendRequest()
does not url-encode raw data). 此外,您的输入JSON字符串似乎在传递给
JSONPostRequest()
之前已经过url编码( HTTPSendRequest()
不会对原始数据进行url编码)。 Don't url-encode the JSON, pass the original JSON as-is. 不要对JSON进行URL编码,按原样传递原始JSON。
Also, INTERNET_SERVICE_HTTP
is not a valid flag for HTTPOpenRequest()
. 此外,
INTERNET_SERVICE_HTTP
不是HTTPOpenRequest()
的有效标志。
You did not show the code that is calling JSONPostRequest()
, so I can't show you how to fix the url-encoding issue. 您没有显示调用
JSONPostRequest()
的代码,因此我无法向您展示如何修复url编码问题。 But try something more like this for the actual post: 但是对于实际的帖子,尝试更像这样的东西:
function WinInetErrorMsg(Err: DWORD): string;
var
ErrMsg: array of Char;
ErrLen: DWORD;
begin
if Err = ERROR_INTERNET_EXTENDED_ERROR then
begin
ErrLen := 0;
InternetGetLastResponseInfo(Err, nil, ErrLen);
if GetLastError() = ERROR_INSUFFICIENT_BUFFER then
begin
SetLength(ErMsg, ErrLen);
InternetGetLastResponseInfo(Err, PChar(ErMsg), ErrLen);
SetString(Result, PChar(ErrMsg), ErrLen);
end else begin
Result := 'Unknown WinInet error';
end;
end else
Result := SysErrorMessage(Err);
end;
function TFormMain.JSONPostRequest(const Server, Url: string; const jo : UTF8String; blnSSL: Boolean): String;
var
aBuffer : Array of Byte;
Header : String;
BufStream : TStringStream;
BytesRead : DWORD;
pSession : HINTERNET;
pConnection : HINTERNET;
pRequest : HINTERNET;
port : Integer;
flags : DWORD;
begin
Result := '';
pSession := InternetOpen(nil, INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if not Assigned(pSession) then
raise Exception.Create('InternetOpen failed. ' + WinInetErrorMsg(GetLastError));
try
if blnSSL then
Port := INTERNET_DEFAULT_HTTPS_PORT
else
Port := 9000;
pConnection := InternetConnect(pSession, PChar(Server), port, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
if not Assigned(pConnection) then
raise Exception.Create('InternetConnect failed. ' + WinInetErrorMsg(GetLastError));
try
if blnSSL then
flags := INTERNET_FLAG_SECURE
else
flags := 0;
pRequest := HTTPOpenRequest(pConnection, 'POST', PChar(Url), nil, nil, nil, flags, 0);
if not Assigned(pRequest) then
raise Exception.Create('HttpOpenRequest failed. ' + WinInetErrorMsg(GetLastError));
try
Header := 'Host: ' + Server + ':' + IntToStr(Port) + #13#10 +
'Content-Type: application/json; charset=UTF-8'#13#10;
if not HttpAddRequestHeaders(pRequest, PChar(Header), Length(Header), HTTP_ADDREQ_FLAG_ADD) then
raise Exception.Create('HttpAddRequestHeaders failed. ' + WinInetErrorMsg(GetLastError));
if not HTTPSendRequest(pRequest, nil, 0, PAnsiChar(jo), Length(jo)) then
raise Exception.Create('HTTPSendRequest failed. ' + WinInetErrorMsg(GetLastError));
SetLength(aBuffer, 4096);
BufStream := TStringStream.Create('', TEncoding.Default);
try
repeat
if not InternetReadFile(pRequest, PByte(aBuffer), Length(aBuffer), BytesRead) then
raise Exception.Create('InternetReadFile failed. ' + WinInetErrorMsg(GetLastError));
if (BytesRead = 0) then Break;
BufStream.WriteBuffer(PByte(aBuffer)^, BytesRead);
until False;
Result := BufStream.DataString;
finally
BufStream.Free;
end;
finally
InternetCloseHandle(pRequest);
end;
finally
InternetCloseHandle(pConnection);
end;
finally
InternetCloseHandle(pSession);
end;
end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.