 |
ActiveDelphi .: O site do programador Delphi! :.
|
Exibir mensagem anterior :: Exibir próxima mensagem |
Autor |
Mensagem |
dmpavan Novato

Registrado: Quinta-Feira, 3 de Fevereiro de 2011 Mensagens: 1
|
Enviada: Qua Set 04, 2019 5:33 pm Assunto: Consumir API |
|
|
Boa Tarde Pessoal!
Se puderem me orientar, preciso consumir uma API (segue documentação... https://api.tudoentregue.com.br/Documentacao/index.html)
Quanto à geração dos arquivo no formato Json, eu já consegui entender.
Porém, já tentei de várias formas e não consigo fechar comunicação com web service para Post do arquivo.
Vi na documentação que tem um "AppKey" e um "RequesterKey". As duas chaves eu possuo mas não tenho ideia de onde as defino.
securityDefinitions": {
"AppKey": {
"type": "apiKey",
"in": "header",
"name": "AppKey",
"description": "Identificador do software Homologado junto à ActiveCorp para integrar dados ao TudoEntregue."
},
"RequesterKey": {
"type": "apiKey",
"in": "header",
"name": "RequesterKey",
"description": "Identificador único do Motorista/Cliente junto ao TudoEntregue."
Estou utilizando IDHTTP, mas seria interessante que o envio fosse através de HTTPS.
Vejam como estou fazendo:
var code : Integer;
sResponse : String;
Json : String;
JsontoSend : TStringStream;
begin
Json := '{"PhoneCountry": "+55", "PhoneNumber": "19999999999", "Name": "Daniel", "IMEI": "", "DeviceKey": "", "DeviceId": "",';
Json := Json +'"DeviceType": "MarcaModelo", "OSName": "Android", "OSVersion": "7.0", "Email": "d2m.pavan@gmail.com", "ZipCode": "13400000", "City": "Piracicaba", "State": "Sao Paulo", "Enable": false}';
JsonToSend := TStringStream.Create(utf8Encode(Json));
try
IdHTTP1.Request.Clear;
IdHTTP1.Request.CharSet := 'UTF-8';
IdHTTP1.Request.Method := 'POST';
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Response.ContentType := 'applicattion/json';
IdHTTP1.Response.CharSet := 'UTF-8';
try
sResponse := IdHTTP1.Post('http://api.tudoentregue.com.br/v1/drivers',JsontoSend);
except
on E:EIdHTTPProtocolException do
begin
Memo1.Lines.Clear;
Memo1.Lines.Add('Error on Request: ' + #13+#10 + e.Message);
exit;
end;
end;
Memo1.Lines.Clear;
Memo1.Lines.Add(sResponse);
finally
JsontoSend.Free();
end;
end;
Alguém poderia me dar um exemplo de como enviar os arquivos se possivel em HTTPS?
Desde já agradeço!
Daniel |
|
Voltar ao Topo |
|
 |
joemil Moderador

Registrado: Quinta-Feira, 25 de Março de 2004 Mensagens: 9100 Localização: Sinop-MT
|
Enviada: Qui Set 05, 2019 9:42 am Assunto: |
|
|
veja este exemplo q usa bearer com um token
Código: | FHttp.Request.CustomHeaders.Clear;
FHttp.Request.Clear;
FHttp.Request.CharSet := 'utf-8';
FHttp.Request.CustomHeaders.AddValue('Content-Type', 'text/xml');
FHttp.Request.CustomHeaders.AddValue('soapaction', 'registrarBoleto');
FHttp.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + FToken); |
_________________ <b>SEMPRE COLOQUE [RESOLVIDO] NO SEU POST</b>
Enviar imagens: http://tinypic.com/ |
|
Voltar ao Topo |
|
 |
rodrigoprado Colaborador

Registrado: Terça-Feira, 24 de Mai de 2005 Mensagens: 1074 Localização: Curitiba/PR
|
Enviada: Qui Set 05, 2019 2:11 pm Assunto: |
|
|
***Usar o postman para testar a api, facilita muito
Abandonei o uso do indy depois de alguns bugs encontrados, faço tudo pelo TRESTClient agora, não precisa se preocupar nesse com httpS, ele faz internamente, vc tb pode usar um teste pelo menu: "Tools > REST Debugger", segue um exemplo com criação dinâmica
Exemplo 01 - soap xml
Código: | {$region 'ExecuteWSTokenExemplo01'}
function ExecuteWSTokenExemplo01(wsUrl, wsXml: WideString; //Alternativa ao envio pelo indy
wsProxyServer: WideString = ''; piProxyPort: Integer = 0;
wsProxyUsername: WideString = ''; wsProxyPassword: WideString = ''): WideString; stdcall; export;
var
restClient: TRESTClient;
restRequest: TRESTRequest;
restResponse: TRESTResponse;
begin
restClient := TRESTClient.Create(wsUrl);
restRequest := TRESTRequest.Create(restClient);
restResponse := TRESTResponse.Create(restClient);
try
try
if wsProxyServer <> '' then
begin
restClient.ProxyServer := wsProxyServer;
restClient.ProxyPort := piProxyPort;
restClient.ProxyUsername := wsProxyUsername;
restClient.ProxyPassword := wsProxyPassword;
end;
restClient.BaseURL := wsUrl;
restRequest.Client := restClient;
restRequest.Method := rmPOST;
restRequest.Resource := '';
restRequest.Response := restResponse;
restRequest.Params.Add;
restRequest.Params[0].ContentType := ctAPPLICATION_XML;
restRequest.Params[0].Kind := pkREQUESTBODY;
restRequest.Params[0].Value := wsXml;
restRequest.Execute;
result := restResponse.Content;
except
on e: Exception do
begin
result := 'Erro retornado pelo webservice: '+ e.Message + ' XML: ' + restResponse.Content;
end
end;
finally
restClient.Free;
end;
end;
{$endregion} |
Exemplo 02 - API JSON
Código: |
{$Region 'ExecuteWSTokenExemplo02'}
function ExecuteWSTokenExemplo02(wsEndpoint, wsResource, wsApiKey, wsBodyJSON: WideString;
wsProxyServer: WideString = ''; piProxyPort: Integer = 0;
wsProxyUsername: WideString = ''; wsProxyPassword: WideString = ''): WideString; stdcall; export;
var
restClient: TRESTClient;
restRequest: TRESTRequest;
restResponse: TRESTResponse;
begin
restClient := TRESTClient.Create(wsEndpoint);
restRequest := TRESTRequest.Create(restClient);
restResponse := TRESTResponse.Create(restClient);
try
try
restClient.BaseURL := wsEndpoint;
if wsProxyServer <> '' then
begin
restClient.ProxyServer := wsProxyServer;
restClient.ProxyPort := piProxyPort;
restClient.ProxyUsername := wsProxyUsername;
restClient.ProxyPassword := wsProxyPassword;
end;
restRequest.Client := restClient;
restRequest.Method := rmPOST;
restRequest.Resource := wsResource;
restRequest.Response := restResponse;
restRequest.Params.Add;
restRequest.Params[0].ContentType := ctAPPLICATION_JSON;
restRequest.Params[0].Kind := pkHTTPHEADER;
restRequest.Params[0].name := 'Content-Type';
restRequest.Params[0].Options := [poDoNotEncode];
restRequest.Params[0].Value := 'application/json';
restRequest.Params.Add;
restRequest.Params[1].ContentType := ctAPPLICATION_JSON;
restRequest.Params[1].Kind := pkHTTPHEADER;
restRequest.Params[1].name := 'apiKey';
restRequest.Params[1].Options := [poDoNotEncode];
restRequest.Params[1].Value := wsApiKey;
restRequest.Params.Add;
restRequest.Params[2].ContentType := ctAPPLICATION_JSON;
restRequest.Params[2].Kind := pkREQUESTBODY;
restRequest.Params[2].Value := wsBodyJSON;
restRequest.Execute;
result := restResponse.Content;
except
on e: Exception do
begin
result := 'Erro: ' + e.Message + ' JSON/TEXT: ' + restResponse.Content;
end
end;
finally
restClient.Free;
end;
end;
{$EndRegion}
|
_________________ - Compartilhe seus conhecimentos - |
|
Voltar ao Topo |
|
 |
|
|
Enviar Mensagens Novas: Proibido. Responder Tópicos Proibido Editar Mensagens: Proibido. Excluir Mensagens: Proibido. Votar em Enquetes: Proibido.
|
|