Questions to the HTTP Get example

86 views
Skip to first unread message

Frank

unread,
May 24, 2024, 3:01:14 PMMay 24
to DroidScript
Hello,

I have two questions to the HTTP Get example:

#1) is there a difference between app.HttpRequest and XMLHttpRequest ?

#2) I need the Authorization: Bearer with an API_KEY,
          ( in curl I use: -H "Authorization: Bearer $API_KEY" ).

Thank you,
BR Frank.



--- HTTP Get example ---

//This sample demonstrates getting a list of UK place names
//within a post code area using the free geonames.org web service.

//Called when application is started.
function OnStart()
{
    //Create a layout with objects vertically centered.
    lay = app.CreateLayout( "linear", "VCenter,FillXY" )   

    //Create an text edit box for postcode entry.
edt = app.CreateTextEdit( "CB1", 0.8 )
lay.AddChild( edt )

    //Create a button to send request.
btn = app.CreateButton( "Get Places", 0.3, 0.1 )
btn.SetMargins( 0, 0.05, 0, 0 )
    btn.SetOnTouch( btn_OnTouch )
lay.AddChild( btn )

    //Create a text label to show results.
    txt = app.CreateText( "", 0.8, 0.6, "Left,Multiline" )
txt.SetBackColor( "#ff222222" )
    txt.SetTextSize( 12 )
    lay.AddChild( txt )
   
    //Add layout to app.   
    app.AddLayout( lay )

}  

//Handle button press.
function btn_OnTouch()
{
    //Get user entered post code.
    var postCode = edt.GetText()
   
    //Send request to remote server.
    var url = "http://api.geonames.org";
    var path = "/postalCodeLookupJSON";
    var params = "postalcode=" + postCode + "|country=UK|username=androidscript";
    app.HttpRequest( "get", url, path, params, HandleReply )
   
    app.ShowProgress( "Loading..." )
}

//Handle the servers reply.
function HandleReply( error, response, status )
{
    txt.SetText( response )
    app.HideProgress()
}

Dave

unread,
May 25, 2024, 5:18:51 AMMay 25
to DroidScript
Generally, I would suggest using standard fetch() or XMLHttpRequest as it is more portable, however the app.HttpRequest() method has the advantage that it can bypass CORS if required.

With app.HttpRequest() You can add your Authorization token to the headers by putting the following string in the last parameter (see the docs)

"Authorization=Bearer " + apiKey

Frank

unread,
May 25, 2024, 8:36:03 AMMay 25
to DroidScript
thank you,

now i am using XMLHttpRequest, it is working fine,

now i can access the TTN, The Things Network - Storage Integration, perfect.

the sample was very helpful:

BR frank.
Reply all
Reply to author
Forward
0 new messages