How to send special characters Delphi 2007?
RogelioGaytan opened this issue · 1 comments
Hi
I'm Having problems making a post call to a rest webservice, i have to send full names of persons, but when they have special characters (like: ñ, á, é, í, ü) it causes error.
For example if you have a name like "Juan Peña López" that have two special characters.
How can I tell the restclient to manage those special characters ?
Here is my code:
function obtenLista(pFullName : String) : WideString;
var
restClient : TRestClient;
lJsonToSend : TStream;
lResponse: WideString;
begin
Try
// If pFullName is for example "Juan Peña López" it throws error
lJsonToSend := TStringStream.Create('{ "fullName" : "' + pFullName + '" }' );
restClient := TRestClient.Create(Nil);
restClient.ConnectionType := hctWinHttp;
restClient.VerifyCert := False;
try
lResponse := restclient.Resource('http://api.url.com/endpoint')
.Accept(RestUtils.MediaType_Json)
.Header('Authorization','Bearer ' + _authToken)
.ContentType('application/json')
.Post(lJsonToSend);
Result := lResponse;
except
on E: Exception do
ShowMessage('Error: ' + #13#10 + e.Message);
end;
Finally
restclient.Free;
lJsonToSend.Free;
End;
end;
If I do the same in Postman with the same input, the server responds correctly, but from delphi it throws the next error
Could not read document: Invalid UTF-8 middle byte 0x70
at [Source: (PushbackInputStream); line: 1, column: 50]; nested exception is com.fasterxml.jackson.core.JsonParseException: Invalid UTF-8 middle byte 0x70
at [Source: (PushbackInputStream); line: 1, column: 50]
Thanks in advance
Ok, so i finally ran into an answer, the solution is to use the overloadd version of the post method that receives an string (intead of TStream), and to that string parameter apply the AnsiToUtf8 function that comes in the System unit
var
lJsonToSend : WideString;
begin
.
.
.
lJsonToSend := AnsiToUtf8('{ "fullName" : "' + pFullName + '" }' );
.
.
.
Response := restclient.Resource('http://api.url.com/endpoint')
.Accept(RestUtils.MediaType_Json)
.Header('Authorization','Bearer ' + _authToken)
.ContentType('application/json')
.Post(lJsonToSend);
And that's it. I hope it helps someone else. let me know.