如何在Windows Phone中传递REST API的用户名和密码

本文关键字:API 用户 密码 REST Windows Phone | 更新日期: 2023-09-27 18:30:03

   public void Execute()       
   {          
        if(this.OnPreExecute!=null)
        {
            this.OnPreExecute();
        }
        HttpWebRequest httpWebRequest = WebRequest.CreateHttp(this.Url);
        //httpWebRequest.Credentials = new NetworkCredential("userName", "password");
        SetBasicAuthHeader(httpWebRequest, userName, password);
        httpWebRequest.Method = "GET";
        httpWebRequest.Accept = "application/json";           
        httpWebRequest.BeginGetResponse(OnGetResponseCompleted, httpWebRequest);
    }
    public void SetBasicAuthHeader(WebRequest httpWebRequest, String userName, String password)
    {            
        string authInfo = userName + ":" + password;
        authInfo = Convert.ToBase64String(Encoding.Unicode.GetBytes(authInfo));
        httpWebRequest.Headers["Authorization"] = "Basic" + authInfo;
    }

考虑到我的用户名为管理员,密码为3。我必须如何传递这些值。

如何在Windows Phone中传递REST API的用户名和密码

WebClient webClient = new WebClient();
        webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        var   uri = new Uri(url, UriKind.Absolute);
        StringBuilder postData = new StringBuilder();
        postData.AppendFormat("{0}={1}", "userName", HttpUtility.UrlEncode(userName));
        postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(password));
        webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
        webClient.UploadStringAsync(uri, "POST", postData.ToString());

感谢回答这个问题的人花费您宝贵的时间。

您只需将用户名凭据方法与该 API 一起传递即可。就像下面一样,

我使用用户名作为manoj,密码作为3

httpWebRequest.Credentials = new NetworkCredential("manoj", "3"(;