Jump to content
Fivewin Brasil

duvida iniciando com API


gibaf

Recommended Posts

Ola a todos

 

eh a primeira vez q estou fazendo o uso de API e ja estou com um problema, nao esta autenticacao 

a documentacao diz passar o seguinte parametro:

-H "X-Requested-With: XMLHttpRequest"

estou fazendo assim:

oUrl:setRequestHeader( "X-Requested-With", "XMLHttpRequest" )

to pra arriscar dizer que o problema esta ai no vermelho, tipo, nao deve ser a string  "XMLHttpRequest" mas sim outra coisa, tipo, algum objeto, algum Handle, ou outra coisa...

 

segue o bloco do fonte:

*-------------------
Function VaiNaNet()
*-------------------
Local oServerWS
Local q      := "pesquisa"
Local qo     := "t"
Local limit  := "60" 
Local page   := "1"
Local cToken := "chaveAcesso"
Local cUrl   := "https://api.site.com/api/v1/busca?q="+q+"&qo="+qo+"&limit="+limit+"&page="+page

oServerWS := CreateObject( "MSXML2.XMLHTTP" )
oServerWS:Open( "GET" , cUrl , .F. )
oServerWS:setRequestHeader( "Authorization"   , "Bearer {"+cToken+"}" )
oServerWS:setRequestHeader( "X-Requested-With", "XMLHttpRequest" )
oServerWS:Send()

? oServerWS:Status          // 401
? oServerWS:StatusText      // erro = nao autenticado
? oServerWS:responseText

Return(Nil)

 

alguem poderia ajudar, por favor ??

 

desde ja fico agradecido: MUITO OBRIGADO !!!

Link to comment
Share on other sites

primeiramente, obrigado Kapiaba pela sua resposta (so nao entendi o significado de "seu post sempre eh confuso"... mas tudo bem..kkkk)

 

pelo q pude entender, o problema eh bem aqui mesmo:

oServerWS:setRequestHeader( "X-Requested-With", "XMLHttpRequest" )

 

parece ter q ser um XML, mas nao faco dei ideia de como tem q ser esse XML

 

 

Link to comment
Share on other sites

Repito a pergunta: https://api.site.com? do que se trata?  esse trem não abre nada ou não existe? Explique.

https://forums.fivetechsupport.com/viewtopic.php?f=3&t=39875&hilit=telegram&start=15

http://forums.fivetechsoft.com/viewtopic.php?t=39448

http://www.fivetechsoft.com/forums/viewtopic.php?t=39875

E por ai vai. Continuo não entendendo que pohha é essa:  https://api.site.com?

Regards, saludos.

Link to comment
Share on other sites

Gibaf, antes de fazer qualquer API o melhor é primeiro simular o funcionamento através do CURL, via linha de comando. Depois de funcionando no CURL vc parte para usar no (x)Harbour.

Do jeito que você postou pode ser milhares de coisas, não da pra saber, principalmente pq vc não colocou quase nenhuma informação na sua pergunta.

Então tente encontrar algum exemplo funcionando em CURL de todo processo primeiro, pq funcionando desta forma vc sabe que a API em si etá correta e ai basta converter a forma de uso pelo CURL para sua aplicação.

Geralmente os desenvolvedores da API disponibilizam sempre exemplos de como se consumir pelo CURL.

 

Link to comment
Share on other sites

13 horas atrás, kapiaba disse:

Repito a pergunta: https://api.site.com? do que se trata?  esse trem não abre nada ou não existe? Explique.

https://forums.fivetechsupport.com/viewtopic.php?f=3&t=39875&hilit=telegram&start=15

http://forums.fivetechsoft.com/viewtopic.php?t=39448

http://www.fivetechsoft.com/forums/viewtopic.php?t=39875

E por ai vai. Continuo não entendendo que pohha é essa:  https://api.site.com?

Regards, saludos.

escavador

Link to comment
Share on other sites

20 horas atrás, giovanyvecchi disse:

Primeiramente você vai ter que aprender a usar o postman https://www.postman.com/

Ele pode gerar as estruturas da api que você deseja.

É complicado, mais vale a pena aprender.

sim.. ja tinha destrassado o conteudo desse link... o problema, q estou vendo, q API nao tem uma manual, tipo, igual o manual da funcao dbUseArea().. cada desenvolvedor da API tem la o seu geito, por mais q tende a ter um padrao...

 

eh o q estou percebendo, mas o meu conhecimento em API eh ZERO (iniciando agora) !

Link to comment
Share on other sites

dbusearea tem uma documentação completa desde a época no NG (Norton Guides) isso ainda nos anos 80. Essa eu realmente não entendi.

Mas segue abaixo um manual completo e com exemplo da função dbusearea

 

DbUseArea()

Opens a database file in a work area.

Syntax

DbUseArea( [<lNewArea>]  , ;
           [<cRddName>]  , ;
           <cDatabase>   , ;
           [<cAlias>]    , ;
           [<lShared>]   , ;
           [<lReadonly>] , ;
           [<cCodePage>] , ;
           [<nConnection>] ) --> NIL

Arguments

<lNewArea>
If .T. (true) is passed for <lNewArea>, the function selects the next unused work area before the database is opened. The default value is .F. (false), which opens the database in the current work area. If the current work area is used, all files are closed before the new database is opened.
<cRddName>
<cRddName> is an optional character string with the name of the RDD to use for opening the database file. It defaults to the return value of RddSetDefault().
<cDatabase>
This is a character string holding the name of the database file to open. It can include path and file extension. The default file extension is DBF.
<cAlias>
This is the symbolic alias name of the work area as a character string. It defaults to the file name of <cDatabase> without extension.
<lShared>
Specifying .T. (true) for <lShared> opens the database in SHARED mode. The default value depends on the SET EXCLUSIVE setting. If set to ON, <lShared> defaults to .F. (false).
<lReadonly>
Specifying .T. (true) for <lReadonly> opens the database in READONLY mode. The default value is .F. (false) which opens the file for read and write access.
<cCodePage>
This is a character string specifying the code page to use for character strings stored in the database. It defaults to the return value of HB_SetCodePage().
<nConnection>
This parameter specifies a numeric server connection handle. It is returned by a server connection function which establishes a connection to a database server, such as SR_AddConnection() of the xHarbour Builder SQLRDD. When <nConnection> is passed, the function opens a database on the server.

Return

The return value is always NIL.

Description

DbUseArea() opens an existing database file named <cDatabase> in the current work area, or in the next unused work area when <lNewArea> is set to .T. (true). The file is searched in the following directories: first in the current directory, then in the SET DEFAULT directory and finally in all directories specified with SET PATH. If the file cannot be found, a runtime error is raised.

When a database is to be accessed in a network, it should be opened in SHARED mode, since EXCLUSIVE usage of a database file prevents other work stations from accessing the file. Shared database access requires to lock a database before changes can be written to a file. Refer to RLock() and FLock() for information about record and file locks in shared database access.

Info

 

See also: CLOSE, DbCloseArea(), NetDbUse(), RddSetDefault(), Select(), SET DEFAULT, SET PATH, Set(), USE
Category: Database functions
Source: rdd\dbcmd.c
LIB: xhb.lib
DLL: xhbdll.dll

Example

// The example opens a database file using command
// and function syntax.

   REQUEST DBFCDX

   PROCEDURE Main
      USE Customer ALIAS Cust NEW
      ? Alias()                        // result: CUST

      DbUseArea( .T., "DBFCDX" , "Orders", "Ord" )
      ? Alias()                        // result: ORD

      CLOSE ALL
   RETURN
Link to comment
Share on other sites

  • 4 weeks later...

Amiguinhos,

Se ter conhecimento do que a API contempla vamos tentar o seguinte(estilo médico em tele-medicina atendendo paciente por telefone, ouvindo sua dor e dando diagnóstico à distância):

No lugar de:

oServerWS:setRequestHeader( "X-Requested-With", "XMLHttpRequest" )

Coloque

oServerWS:setRequestHeader( "Content-Type", "application/xml;charset=UTF-8" )
   oServerWS:setRequestHeader( "Accept", "application/xml" )

Como você está usando a passagem de argumentos diretamente pela URL você usa o protocolo GET e a função send() sem parâmetros. Caso precise passar um trecho XML você deverá usar protocolo POST e lançar o conteúdo pela função send( conteudo ).

Se a API fornece exemplo via CURL, faça o download e instale-o e use diretamente pela linha de comando para testar(como alertado por forense) e depois implemente via código usando os recursos da linguagem.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...