简体   繁体   中英

Add header to http request

My first post here. I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.

That's the code I'm using:

function btn_OnTouch(){

    var url = "myurl";
    SendRequest(url);

}

//Send an http get request.

function SendRequest(url){

    var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function() {
        HandleReply(httpRequest);
    };

    httpRequest.open("GET", url, true);

    httpRequest.send(null);

    app.ShowProgress("Loading...");

}

//Handle the servers reply (a json object).

function HandleReply(httpRequest){

    if (httpRequest.readyState == 4){

        //If we got a valid response.

        if (httpRequest.status == 200){
            txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
        }

        //An error occurred
        else
            txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);

    }

    app.HideProgress();

}

The told me I should probably include the headers like this, but I don't know where to put them in my code.

httpRequest.setRequestHeader(“username”, “myuser”);

httpRequest.setRequestHeader(“password”, “mypass”);

You need to do it just after calling the open method like this:-

httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM