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

时间:2014-11-12 09:37:50

标签: c# wpf windows-phone-8 windows-phone

   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;
    }

考虑我的用户名为admin,密码为3.我如何传递这些值。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

感谢谁回答这个问题花了你宝贵的时间。

您只需要传递用户名凭据方法以及该API。如下所示,

我使用Username作为manoj,密码作为3

httpWebRequest.Credentials = new NetworkCredential(“manoj”,“3”);