I use THTTPClient instead of Indy to get a Json value from my API. I do it like this :
Url := 'http://example.com/api/index.php?get&latitude=' +
TNetEncoding.Base64.Encode(MapView.Location.Latitude.ToString)
+ '&longitude=' + TNetEncoding.Base64.Encode(MapView.Location.Longitude.ToString);
Json := TToolHTTP.Get(Url);
The method to get is write below :
class function TToolHTTP.Get(aUrl: string): string;
var
Client : THTTPClient;
Response: IHTTPResponse;
begin
Result := '';
Client := THTTPClient.Create;
try
try
Response := Client.Get(aUrl);
Result := Response.ContentAsString;
except
ShowMessage('Error');
end;
finally
FreeAndNil(Client);
end;
end;
The first time or two first time I get my Json value, the third time I call this method with same url I get the content of the root page (http://example.com/index.html), and then when I call it the 4 time I get my Json. It's look like really random, but for sure I always get a Status Code HTTP 200.
Why sometime I get the html of the root page ?
Related
I'm trying to send JSON POST request to an API using a TRESTClient (Delphi 10.4/Windows 10), but I'm receiving a 409 conflict indicating "No input found". Using the same code in (Delphi XE6/Windows 10) I get a REST request failed: Socket Error # 10054 Connection reset by peer.. Using WireShark I was able to see that Delphi XE6 was sending the request with TLS 1.0 and Delphi 10.4 is using TLS v1.2. The API service accepts only TLS v1.2. Is there a way to use these REST components in Delphi XE6 to deliver the request with TLS 1.2?
I beleived my problem was that I was JSON encoding all the input with the code:
// Assign JSON
sl := TStringList.Create;
sl.Add('locations=[{"address":"Test1","lat":"52.05429","lng":"4.248618"},{"address":"Test2","lat":"52.076892","lng":"4.26975"},{"address":"Test3","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, The Netherlands","lat":"51.589548","lng":"5.432482"}]');
and then assigning it to the Request Body with RESTRequest.AddBody(sl);, whereas the API only expects the value of the locations parameter to be JSON.
I have updated the code to assign the JSON to a String and used the RESTRequest.Params.Items[0].name := 'locations'; and RESTRequest.Params.Items[0].Value := s; to add the string to the request body.
Here's my updated code:
procedure TMainForm.btn_RouteXL_PostClick(Sender: TObject);
var
s, sResult, AError: String;
jsObj: TJSONObject;
AJSONValue, jsResponse: TJSONValue;
AParameter: TRESTRequestParameter;
AStatusCode: Integer;
begin
//ResetRESTComponentsToDefaults;
s := '[{"address":"Test1","lat":"52.05429","lng":"4.248618"},{"address":"Test2","lat":"52.076892","lng":"4.26975"},{"address":"Test3","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, The Netherlands","lat":"51.589548","lng":"5.432482"}]';
RESTClient.BaseURL := 'https://api.routexl.com/tour';
RESTClient.ContentType := 'ctAPPLICATION_X_WWW_FORM_URLENCODED';
RESTClient.Authenticator := HTTPBasic_RouteXL;
RESTRequest.Method := TRESTRequestMethod.rmPOST;
RESTRequest.Params.AddItem; //Adds a new Parameter Item
RESTRequest.Params.Items[0].name := 'locations'; //sets the name of the parameter. In this case, since I need to use 'locations=' on the request, the parameter name is locations.
RESTRequest.Params.Items[0].Value := s; //Adds the value of the parameter, in this case, the JSON data.
RESTRequest.Params.Items[0].ContentType := ctAPPLICATION_X_WWW_FORM_URLENCODED; //sets the content type.
RESTRequest.Params.Items[0].Kind := pkGETorPOST; //sets the kind of request that will be executed.
RESTRequest.Execute;
try
memo_ResponseData.Lines.Add('************JSONText*******************');
memo_ResponseData.Lines.Add(RESTResponse.JSONValue.ToString);
//Memo1.Lines.Add('JSONValue :'+RESTResponse.JSONValue.Value);
memo_ResponseData.Lines.Add('StatusText :'+RESTRequest.Response.StatusText );
memo_ResponseData.Lines.Add('StatusCode :'+IntToStr(RESTRequest.Response.StatusCode ));
memo_ResponseData.Lines.Add('ErrorMesage:'+RESTRequest.Response.ErrorMessage);
memo_ResponseData.Lines.Add('************Content*******************');
memo_ResponseData.Lines.Add(RESTRequest.Response.Content);
memo_ResponseData.Lines.Add('************Headers*******************');
memo_ResponseData.Lines.Add(RESTRequest.Response.Headers.Text);
except
on E: Exception do
begin
memo_ResponseData.Lines.Add('************Error*******************');
memo_ResponseData.Lines.Add('Error : ' +E.Message);
memo_ResponseData.Lines.Add(E.ClassName);
memo_ResponseData.Lines.Add('************Error*******************');
memo_ResponseData.Lines.Add('Error : '+RESTResponse.Content);
end;
end;
end;
I'm able to get it to work in Postman using a key-value pair, by assigning the key as locations and the value as the contents of sl as seen in the screenshot. But I'm unable to translate that to Delphi.
I'm trying to write a function that will insert informations in my database using JSON or multiple parameters in the URL.
I already managed to create a function that returns informations from my database to the client but not the other way. Every example I find explains how to creat a JSON but not how to receive it with System.JSON (Delphi 10.2)
Here is a code sample for a GET function actually working on my Datasnap :
function TDM_Test.DS_getArticles(pStock : String): string;
begin
try
VGOutils.PR_logs('Get all articles from table');
VGOutils.FU_CheckConnect('1234567890');
with VGOutils.SQ_temp1 do
begin
SQL.Clear;
SQL.Add('SELECT code, name, price, seller, departement FROM articles');
SQL.Add('WHERE stock');
ParamByName('stock').AsString := pStock;
VGOutils.SQ_temp1.Open;
end;
GetInvocationMetadata().ResponseCode := 200;
GetInvocationMetadata().ResponseContent :=
VGOutils.PR_JSON(VGOutils.SQ_temp1, ['code', 'name', 'price', 'seller']);
except on E: Exception do
PR_error(E.Message);
end;
VGOutils.PR_Disconnect;
end;
Now I need the client to send me new articles to INSERT in my database.
The only thing that I cant figure out is how to declare the function and it's parameters.
I want the client to be able to send me a JSON with this correct format
{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}
Now I know how to parse it with TJSONObject.ParseJSONValue() by reading this JSON RadStudio
EDIT
If this JSON string is hardcoded it works fine with ParseJSONValue but if the string is taken from the URL my JSONstring only contains "]}" and obviously there is nothing to parse.
function TDM_Test.DS_insertArticles(pUrlJsonString: String): string;
// Hardcoded JSON string
jsonString := '{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}';
JSonValue := TJSONObject.ParseJSONValue(jsonString);
// String received in url
jsonString := pUrlJsonString;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonString);
I found the way I wanted it to work by not using the string parameter of the function but instead using the Custom body by passing a JSONObject.
The method is POST and the content type is application/JSON.
function TDM_Test.DS_insertArticles(pUrlJsonObj: TJSONObject): string;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonObj);
// Retrieve data for database fields
artCode := JSONValue.GetValue<string>('article[0].code');
artName := JSONValue.GetValue<string>('article[0].name');
artPrice := JSONValue.GetValue<string>('article[0].price');
//... Proceed to INSERT SQL with these values
source gives socket error 14001, WITH OBJ JSON PARAM MESSAGE FOR POST
jso := TlkJSONobject.Create; // (data) as TlkJSONobject;
jso.Add('InvoiceNumber', '');
jso.Add('POSID', '910441');
jso.add('USIN', ePOSNo.Text);
jso.add('DATETIME', eDate.Text);
IdHTTP1.Request.Accept := 'application/json';
IdHTTP1.Request.ContentType := 'application/json';
{ Call the Post method of TIdHTTP and read the result into TMemo }
Memo1.Lines.Text := IdHTTP1.Post('http://localhost;8524/api/IMSFISCAL/GetInvoiceNumberByModel', JSO);
json cannot be passed as tstream
need help on it
There is no way the code you showed can produce a socket error (let alone error 14001, which is not even a socket error) since the code won't even compile!
The TIdHTTP.Post() method does not have an overload that accepts a TlkJSONobject as input. How could it? TlkJSONobject comes from a completely different 3rd party library, it is not part of the RTL or Indy. The only things you can POST with TIdHTTP are:
TStrings-derived types
TStream-derived types, including Indy's TIdMultiPartFormDataStream
a file specified by a String filename
In this case, you need to use a TStream to post JSON stored in memory. It is your responsibility to save your TlkJSONobject content to a suitable TStream of your choosing. That is outside the scope of Indy. For instance, you can use TlkJSON.GenerateText() to get the JSON into a String and then POST it using a TStringStream.
On a side note, the URL you are passing to TIdHTTP.Post() is malformed. The correct delimiter between a hostname and port number is a colon (:), not a semicolon (;).
With that said, try this:
jso := TlkJSONobject.Create;
jso.Add('InvoiceNumber', '');
jso.Add('POSID', '910441');
jso.add('USIN', ePOSNo.Text);
jso.add('DATETIME', eDate.Text);
IdHTTP1.Request.Accept := 'application/json';
IdHTTP1.Request.ContentType := 'application/json';
{ Call the Post method of TIdHTTP and read the result into TMemo }
PostData := TStringStream.Create(TlkJSON.GenerateText(jso), TEncoding.UTF8);
try
Memo1.Lines.Text := IdHTTP1.Post('http://localhost:8524/api/IMSFISCAL/GetInvoiceNumberByModel', PostData);
finally
PostData.Free;
end;
On to more curious challenges in the Delphi/Indy/TWebBrowser/Tableau saga.
I'm having a very hard time understanding why sending a GET request to the Tableau server utilizing the TIdHttp component always returns a JSON response, while the same request in a TWebBrowser control with the same auth header returns an XML response.
I slightly prefer XML - even though it is more bandwidth intensive - since we have much XML infrastructure and currently no JSON infrastructure.
When I send the request with the TIdHttp component, I'm sending it with the following params:
http.Request.CustomHeaders.Text := GetAuthHeader(FToken);
http.Request.ContentType := 'application/json';
I've also tried this:
http.Request.ContentType := 'text/xml';
http.Request.Accept := 'text/xml';
And
http.Request.ContentType := 'application/xml';
http.Request.Accept := application/xml';
And
<no settings specified for accept and contenttype, just let it use the defaults>
...
sHTML := http.Get('http://<myserver>/api/3.0/sites/' + FSiteId + '/views')
...and always receive back the response in JSON.
When I send the same request with TWebBrowser:
var
hdr,flags,targetframe,postdata,Aurl: OleVariant;
begin
AUrl := http://<myserver>/api/3.0/sites/' + FSiteId + '/views';
flags := navNoHistory+navNoReadFromCache+navNoWriteToCache;
targetframe := 1;
postdata := 1;
hdr := GetAuthHeader(FToken);
Navigate2(Aurl,flags,targetframe,postdata,hdr);
end;
...the response always comes back as XML.
Does anyone understand why this would occur? I've tried logging the raw request to see how it's being set up by TWebBrowser, but can't seem to get the raw request. Perhaps I should set up a proxy server...
TIA
Solved - had a
http.Request.ContentType := 'application/json...';
and a
http.Request.Accept := 'application/json...';
still hanging around from the form create event.
I have encountered a few sites that uses JSON for request and response
I come across two types :
1- application/x-www-form-urlencoded as request and return a response application/json content type
2- application/json content type for both request and response
in type 1 i tried changing the the response content type using
mIdHttp.Response.ContentType := 'application/json';
but using http analyzer i can see that it doesn't change and its still text/html
now i do not know if the problem is with the fact that i can't change content type or not but i do not know how to deal with json !
a few question regarding json :
1- do i have to encode json data when posting ? how ?
2- how can i parse the json response code ? how to get it ? does it need some kind of encode or special convertion ?
3- what kind of idhttp setting for json changes with each site and needs configuring ?
I understand my questions sound a bit general, but all the other questions are very specific and don't explain the basics when dealing with 'application/json' content type.
Edit 1 :
thanks to Remy Lebeau answer i was able to successfully work with type 1
but i still have trouble sending JSON request, can someone please share an working example, this is one of the sites posting information please use this for your example :
One important note : this particular site's post and request content are exactly like each other ! and it baffles me because at the site, i specify an start date and an end date then click on a folder like icon and this post is sent (the one you can see above), and the result should be links (and it is) but instead of appearing only in request content they also appear in post ! (also i'm trying to get the links but at the post the links, the thing i want, are also being sent, how can i post something i don't have !!?)
just for more clarity here is the place i fill the date and the icon i mentioned :
You cannot specify the format of the response, unless the requested resource offers an explicit input parameter or dedicated URL for that exact purpose (ie, to request a response be sent as html, xml, json, etc). Setting the TIdHTTP.Response.ContentType property is useless. It will be overwritten by the actual Content-Type header of the response.
To send JSON in a request, you must post it as a TStream, like TMemoryStream or TStringStream, and set the TIdHTTP.Request.ContentType as needed, eg:
var
ReqJson: TStringStream;
begin
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Post(URL, ReqJson);
finally
ReqJson.Free;
end;
end;
To receive JSON, TIdHTTP can either
return it as a String (decoded using a server-reported charset):
var
ReqJson: TStringStream;
RespJson: String;
begin
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
RespJson := IdHTTP1.Post(URL, ReqJson);
finally
ReqJson.Free;
end;
// use RespJson as needed...
end;
write the raw bytes to an output TStream of your choosing:
var
ReqJson: TStringStream;
RespJson: TMemoryStream;
begin
RespJson := TMemoryStream.Create;
try
ReqJson := TStringStream.Create('json content here', TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
RespJson := IdHTTP1.Post(URL, ReqJson, RespJson);
finally
ReqJson.Free;
end;
RespJson.Position := 0;
// use RespJson as needed...
finally
RespJson.Free;
end;
end;
The HTTP response code is available in the TIdHTTP.Response.ResponseCode (and TIdHTTP.ResponseCode) property.