将标头添加到http请求

时间:2016-10-06 15:43:51

标签: javascript android rest http get

我在这里的第一篇文章。 我使用droidscript,我必须包含一个包含特定用户和密码的标头,以便检索令牌。我遇到了麻烦,因为我不知道在哪里加入这些标题。

我正在使用的代码:

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();

}

告诉我,我应该包括这样的标题,但我不知道将它们放在我的代码中的哪个位置。

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

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

1 个答案:

答案 0 :(得分:0)

您需要在调用open方法之后立即执行此操作: -

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