HttpWebResponse 401-错误未经授权

HttpWebResponse 401-error Unauthorized

我目前在尝试调用 API 时遇到 HttpWebRequest/Response 的问题。

API是用JSON/Ajax来调用的,但是我需要通过HttpWebRequest/Response来调用,我不是很懂,我觉得我传错了访问令牌。

这是我从教程中获得的当前代码:

        byte[] buffer = Encoding.ASCII.GetBytes("username=User&password=Password");

        HttpWebRequest WebReq =(HttpWebRequest)WebRequest.Create("http://api40.maildirect.se/User/Authorize");

        WebReq.Method = "POST";
        WebReq.ContentType = "application/x-www-form-urlencoded";
        WebReq.ContentLength = buffer.Length;

        Stream PostData = WebReq.GetRequestStream();

        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

        var status = WebResp.StatusCode; (returns OK)

        Stream _Answer = WebResp.GetResponseStream();
        StreamReader Answer = new StreamReader(_Answer);

        //Here I try to make another request, do I need to make another instance?
        WebReq = (HttpWebRequest)WebRequest.Create("http://api40.maildirect.se/Contacts?&select=ContactId,FirstName,LastName");
        WebReq.Method = "GET";
        WebReq.ContentType = "text/json; charset=utf-8";
        WebReq.Headers.Add("Authorization", Answer.ReadToEnd());

        HttpWebResponse WebResp2 = (HttpWebResponse)WebReq.GetResponse();

         ^ This is where it breaks because I'm not authorized.

API 中唯一有用的文档是我需要在进行其他调用时传递访问令牌,但我怀疑我传递了错误的令牌。

提前致谢

deSex

我发送的是 HttpWebResponse 作为令牌,而不是 StreamReader 产生的字符串。我用这个字符串值创建了一个名为 token 的新变量,并将其添加到 header "Authorization" 中。

        byte[] buffer = Encoding.ASCII.GetBytes("username=Username&password=Password");
        HttpWebRequest WebReq = (HttpWebRequest) WebRequest.Create("http://api40.maildirect.se/User/Authorize");

        WebReq.Method = "POST";
        WebReq.ContentType = "application/x-www-form-urlencoded";
        WebReq.ContentLength = buffer.Length;

        Stream PostData = WebReq.GetRequestStream();

        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        HttpWebResponse WebResp = (HttpWebResponse) WebReq.GetResponse();

        //This token variable was something I missed creating and it also had to get the " removed to work properly.
        var token = new StreamReader(WebResp.GetResponseStream()).ReadToEnd().Replace("\"", "");

        WebReq = (HttpWebRequest) WebRequest.Create("http://api40.maildirect.se/Contacts");

        WebReq.Method = "GET";
        WebReq.ContentType = "application/json; charset=utf-8";

        // This is where another part of the problem was, sent in the wrong type to the header, but when I replaced it with the token variable it worked like a charm :)
        //WebReq.Headers.Add("Authorization", WebResp.ToString());

        WebReq.Headers.Add("Authorization", token);

        HttpWebResponse WebResp2 = (HttpWebResponse) WebReq.GetResponse();