How to get the request header from TNetHTTPClient?
I have the following code:
var
netC: TNetHTTPClient;
strim: TStringStream;
aResponse: IHTTPResponse;
begin
netC := TNetHTTPClient.Create(nil);
try
strim := TStringStream.Create;
try
aResponse := netC.Get('https://google.com', strim);
finally
strim.Free;
end;
finally
netC.Free;
end;
end;
Related
How can I retrieve a JSON result from a HTTPS site?
I prefer a method to no need any DLL.
It show this error:
Error connecting with SSL.error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version.
I'm using Delphi Tokyo 10.2.
function GetUrlContent(s: string): string;
var
IdHTTP1: TIdHTTP;
begin
IdHTTP1 := TIdHTTP.Create;
try
Result := IdHTTP1.Get(s);
finally
IdHTTP1.Free;
end;
end;
procedure GetData;
var
mydata, ordername: string;
begin
ordername := 'https://www.bitstamp.net/api/ticker/';
mydata := GetUrlContent(ordername);
DBMemo7.Text := mydata;
end;
I've also tried this, but it still gets the annoying SSL error:
function GetURLAsStrin1(const aurl: string): string;
var
res, req: String;
sList: TStringList;
IdHttp: TIdHttp;
begin
IdHttp := TIdHttp.Create (nil);
try
IdHttp.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHttp);
req := aurl;
res := IdHttp.Get (req);
result := res;
finally
idHttp.Free;
end;
By default, TIdSSLIOHandlerSocketOpenSSL enables only TLS 1.0. Most likely, the site in question does not support TLS 1.0 anymore. Try enabling TLS 1.1 and 1.2, eg:
function GetUrlContent(url: string): string;
var
IdHTTP1: TIdHTTP;
begin
IdHTTP1 := TIdHTTP.Create;
try
IO := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
IO.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2] // <-- add this!
IdHttp.IOHandler := IO;
Result := IdHTTP1.Get(url);
finally
IdHTTP1.Free;
end;
end;
For newer delphi versions, I would recommend using the in-built HttpClient class. It does not require any external DLLs, and works for both http or https out of the box.
uses
System.Net.HttpClient;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Text := GetUrlContent('https://www.bitstamp.net/api/ticker/');
end;
function TForm1.GetUrlContent(Url: string): string;
var
HttpClient: THttpClient;
Response: IHttpResponse;
begin
HttpClient := THTTPClient.Create;
try
Response := HttpClient.Get(URL);
Result := Response.ContentAsString();
finally
HttpClient.Free;
end;
end;
I'm doing a HTTPS post with this code to azurewebsites.
http://MYAPP.azurewebsites.net/api/MYFUNC
I'm currently using this code:
procedure TForm1.OriginalTest();
var
lHTTP: TIdHTTP;
HTTPResult: string;
RequestBody: TStream;
URL: String;
Body: string;
IOHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
lHTTP := TIdHTTP.Create;
try
Body := '{}';
RequestBody := TStringStream.Create(Body, TEncoding.UTF8);
lHTTP.Request.Accept := '';
lHTTP.Request.UserAgent := '';
lHTTP.Request.CustomHeaders.Add('x-functions-key:<your api key>');
lHTTP.ConnectTimeout := 24000;
lHTTP.ReadTimeout := 24000;
IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
IOHandler.SSLOptions.Method := sslvTLSv1_2;
lHTTP.IOHandler := IOHandler;
try
URL := 'https://<yourapp>.azurewebsites.net/api/<funcname>';
HTTPResult := lHTTP.Post(url, RequestBody);
Memo1.Lines.Add(HTTPResult);
except
on E:Exception do
begin
Memo1.Lines.Add(Format('Error sending data. Error: %s', [E.Message] ));
end;
end;
finally
lHTTP.Free;
RequestBody.Free;
end;
end;
For whatever reason, this code gives me the following error:
Error sending data. Error: Socket Error # 10054 Connection reset by peer.
I tried making a simple HTTPS Post using .NET with HttpWebRequest , and it works fine. What am I doing wrong here?
I just gave up and used WinApi.WinInet instead.
I'm facing a problem to send messages to all of my friends in the list, when I hit the send button only the first person in the list receives (2) notification messages!!!, there are 2 IDs in the list, using GCM service, why the message is not send to all?
this the codes, plz HELP...
const
YOUR_GCM_SENDERID = '123201xxx95';
YOUR_API_ID = 'AIzaSyBzvpTa-e0OnkaxxxxXfH6XroXN8QE';
procedure TForm1.Button5Click(Sender: TObject);
const
sendUrl = 'https://android.googleapis.com/gcm/send';
var
Params: TStringList;
AuthHeader: STring;
idHTTP: TIDHTTP;
SSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
i : integer;
ItemText: string;
begin
idHTTP := TIDHTTP.Create(nil);
SslIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
idHTTP.IOHandler := SSLIOHandler;
idHTTP.HTTPOptions := [];
Params := TStringList.Create;
for i := 0 to ListView1.Items.Count-1 do
begin
ItemText := ListView1.Items[i].Text;
Params.Add('registration_id='+ ItemText);
Params.Values['data.message'] := Edit1.Text;
idHTTP.Request.Host := sendUrl;
AuthHeader := 'Authorization: key=' + YOUR_API_ID;
idHTTP.Request.CustomHeaders.Add(AuthHeader);
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded;charset=UTF-8';
idHTTP.Post(sendUrl, Params);
end;
FreeAndNil(idHTTP);
end;
You are not managing your parameters correctly on each loop iteration. In particular, you are not overwriting the registration_id value in Params, or the Authorization value in TIdHTTP.Request.CustomHeaders. You are adding new values and keeping the previous values.
Try something more like this instead:
const
YOUR_GCM_SENDERID = '123201xxx95';
YOUR_API_ID = 'AIzaSyBzvpTa-e0OnkaxxxxXfH6XroXN8QE';
procedure TForm1.Button5Click(Sender: TObject);
const
sendUrl = 'https://android.googleapis.com/gcm/send';
var
Params: TStringList;
idHTTP: TIdHTTP;
SSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
i : integer;
ItemText: string;
begin
idHTTP := TIDHTTP.Create(nil);
SslIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(idHTTP);
idHTTP.IOHandler := SSLIOHandler;
idHTTP.HTTPOptions := [];
Params := TStringList.Create;
for i := 0 to ListView1.Items.Count-1 do
begin
ItemText := ListView1.Items[i].Text;
Params.Clear;
Params.Add('registration_id='+ ItemText);
Params.Add('data.message=' + Edit1.Text);
idHTTP.Request.CustomHeaders.Values['Authorization'] := 'key=' + YOUR_API_ID;
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded;charset=UTF-8';
idHTTP.Post(sendUrl, Params);
end;
end;
I am trying to post data to bing with this code
function PostExample: string;
var
lHTTP: TIdHTTP;
lParamList: TStringList;
begin
lParamList := TStringList.Create;
lParamList.Add('q=test');
lHTTP := TIdHTTP.Create(nil);
try
Result := lHTTP.Post('http://www.bing.com/', lParamList);
finally
FreeAndNil(lHTTP);
FreeAndNil(lParamList);
end;
end;
And then, how can I get the result to the TWebBrowser and display it?
Try LoadDocFromString:
procedure LoadBlankDoc(ABrowser: TWebBrowser);
begin
ABrowser.Navigate('about:blank');
while ABrowser.ReadyState <> READYSTATE_COMPLETE do
begin
Application.ProcessMessages;
Sleep(0);
end;
end;
procedure CheckDocReady(ABrowser: TWebBrowser);
begin
if not Assigned(ABrowser.Document) then
LoadBlankDoc(ABrowser);
end;
procedure LoadDocFromString(ABrowser: TWebBrowser; const HTMLString: wideString);
var
v: OleVariant;
HTMLDocument: IHTMLDocument2;
begin
CheckDocReady(ABrowser);
HTMLDocument := ABrowser.Document as IHTMLDocument2;
v := VarArrayCreate([0, 0], varVariant);
v[0] := HTMLString;
HTMLDocument.Write(PSafeArray(TVarData(v).VArray));
HTMLDocument.Close;
end;
Or you can use the memory streams for loading
uses
OleCtrls, SHDocVw, IdHTTP, ActiveX;
function PostRequest(const AURL: string; const AParams: TStringList;
const AWebBrowser: TWebBrowser): Boolean;
var
IdHTTP: TIdHTTP;
Response: TMemoryStream;
begin
Result := True;
try
AWebBrowser.Navigate('about:blank');
while AWebBrowser.ReadyState < READYSTATE_COMPLETE do
Application.ProcessMessages;
Response := TMemoryStream.Create;
try
IdHTTP := TIdHTTP.Create(nil);
try
IdHTTP.Post(AURL, AParams, Response);
if Response.Size > 0 then
begin
Response.Position := 0;
(AWebBrowser.Document as IPersistStreamInit).Load(
TStreamAdapter.Create(Response, soReference));
end;
finally
IdHTTP.Free;
end;
finally
Response.Free;
end;
except
Result := False;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Params: TStringList;
begin
Params := TStringList.Create;
try
Params.Add('q=test');
if not PostRequest('http://www.bing.com/', Params, WebBrowser1) then
ShowMessage('An unexpected error occured!');
finally
Params.Free;
end;
end;
i want to post data to the following url:
http://mehratin.heroku.com/personals/new
i write the following code but has problem:
procedure TForm1.Button3Click(Sender: TObject);
var
aStream: TMemoryStream;
Params: TStringList;
begin
aStream := TMemoryStream.Create;
Params := TStringList.Create;
try
with IdHTTP1 do
begin
Params.Add('fname=123');
Params.Add('lname=123');
Request.ContentType := 'application/x-www-form-urlencoded';
try
Response.KeepAlive := False;
Post('http://localhost:3000/personals/new', Params);
except
on E: Exception do
showmessage('Error encountered during POST: ' + E.Message);
end;
end;
how can i post data by TIDHtttp.post method in delphi 2010?
First things first, you'd need to read the http response code (it would have been useful to include that in your question).
In the absence of that I've used the Indy http object before as shown below. I included the parameters in my URL though. To troubleshoot, try running this with an http.Get to ensure the port is open, and you can actually connect to the server. Here's my example for completenes:
// parameters
params := format('export=1&format=%s&file=%s', [_exportType, destination]);
// First setup the http object
procedure TCrystalReportFrame.SetupHttpObject();
begin
try
IDHTTP1.HandleRedirects := TRUE;
IDHTTP1.AllowCookies := true;
IDHTTP1.Request.CacheControl := 'no-cache';
IdHTTP1.ReadTimeout := 60000;
_basePath:= GetBaseUrl;
except
on E: Exception do
begin
Global.LogError(E, 'SetupHttpObject');
end;
end;
end;
// Then have an onwork event
procedure TCrystalReportFrame.HttpWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
Http: TIdHTTP;
ContentLength: Int64;
Percent: Integer;
begin
Http := TIdHTTP(ASender);
ContentLength := Http.Response.ContentLength;
end;
// The actual process
procedure TCrystalReportFrame.ProcessHttpRequest(const parameters: string);
var
url : string;
begin
try
try
SetupHttpObject;
IdHTTP1.OnWork:= HttpWork;
url := format('%s&%s', [_basePath, parameters]);
url := IdHTTP1.Post(url);
except
on E: Exception do
begin
Global.LogError(E, 'ProcessHttpRequest');
end;
end;
finally
try
IdHTTP1.Disconnect;
except
begin
end;
end;
end;
end;