Forcing Basic Authentication in WebRequest

后端 未结 4 663
春和景丽
春和景丽 2020-12-02 11:57

I am integrating web service that will use an HTTP-POST to request and retrieve data. The remote server requires basic authentication as per RFC 2617

My attempts to

4条回答
  •  有刺的猬
    2020-12-02 12:40

    I've just found this very handy little chunk of code to do exactly what you need. It adds the authorization header to the code manually without waiting for the server's challenge.

    public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic " + authInfo;
    }
    

    Use it like this

    var request = WebRequest.Create("http://myserver.com/service");
    SetBasicAuthHeader(request, userName, password);
    
    var response = request.GetResponse();
    

提交回复
热议问题