我正在使用Delphi 2010向Java應用程序發送HTTP請求。具體來說,我發送一個JSON對象。但是,在發送請求時,我不知道發生了什麼,但該對象不正確。使用Delphi上的Wininet API進行HTTP POST
我發送的對象是這樣的:
{"entidad":"1","username":"A","password":"1234"}
我的嗅探器讀取這樣的對象:
%�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�
因此,我的Java應用程序不讀取對象,它導致空指針例外。
我的代碼是在這裏:
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;
謝謝,雷米。這段代碼幫助我解決了我的問題。 –
@ FelipeCeballos-Desystec然後,您可以通過點擊此帖子左下方的複選標記來接受答案。 – RepeatUntil
謝謝,@AbdulrahmanAljehani。我已經做到了。 –