HttpWebResponse 401-error未经授权

时间:2015-02-18 09:28:33

标签: c# api httpwebrequest token httpwebresponse

当我尝试调用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

1 个答案:

答案 0 :(得分:0)

我发送了HttpWebResponse作为令牌,而不是StreamReader产生的字符串。我用这个字符串值创建了一个名为token的新变量,并将其添加到标题" 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();