使用 HttpWebRequest 发送凭据

本文关键字:HttpWebRequest 使用 | 更新日期: 2023-09-27 18:36:45

我目前正在尝试使用Wunderlist中的API在Windows Phone 8上制作待办事项列表。但是,我无法在 POST 请求中传递我的凭据。这是我的代码:

public async Task<System.IO.TextReader> DoRequestAsync(WebRequest request)
    {
            var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res =>
                    ((HttpWebRequest)res.AsyncState).EndGetResponse(res), request);
            var result = await task;
            var response = result;
            var stream = response.GetResponseStream();
            var sr = new System.IO.StreamReader(stream);
        return sr;
    }

和:

public async Task<System.IO.TextReader> Login(string email, string password)
    {
        //User Credentials
        WebClient client = new WebClient();
        var parms = new Dictionary<string, string>();
        parms.Add(email, password);

        //Request
        HttpWebRequest request = HttpWebRequest.CreateHttp(API_URL + "/login");
        request.AllowReadStreamBuffering = true;
        request.Method = HttpMethod.Post;
        // This doesn't seem to work
        request.Credentials = new NetworkCredential(email, password);
        var tr = await DoRequestAsync(request);
        return tr;
    }
    private string DictToString(Dictionary<string, string> dict)
    {
        StringBuilder builder = new StringBuilder();
        foreach(KeyValuePair<string, string> kvp in dict)
        {
            builder.Append(kvp.Key + "=" + kvp.Value + "&");
        }
        return builder.ToString();
    }

感谢帮助

使用 HttpWebRequest 发送凭据

删除带有.credentials的字符串,因为NetworkCredential适用于NTLM/Kerberos,这里是带有通常POST的api。

在发送请求之前添加:

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write("email=" + HttpUtility.UrlEncode(email));
    writer.Write("&password=" + HttpUtility.UrlEncode(password));
}