【问题标题】:errors running HttpWebRequest.GetResponse - 401 unauthorized运行 HttpWebRequest.GetResponse 时出错 - 401 未经授权
【发布时间】:2015-03-05 19:26:11
【问题描述】:

我正在使用 Lymbix 客户端库进行情绪分析。 当我运行代码时,我在 (WebResponse)httpRequest.GetResponse(): 401-Unauthorized 中遇到错误

(可在https://github.com/lymbix/.NET-Wrapper 获得)

包含401错误的函数如下:

    private static string Post(string url, string data, List<string> headers)
    {
        HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.Accept = "application/json";
        httpRequest.ContentType = "application/x-www-form-urlencoded";

        if (headers != null)
        {
            foreach (string header in headers)
            {
                httpRequest.Headers.Add(header);
            }
        }

        // write request?

        byte[] postData = Encoding.UTF8.GetBytes(data.ToString());
        httpRequest.ContentLength = postData.Length;
        httpRequest.GetRequestStream().Write(postData, 0, postData.Length);

        // read response
        WebResponse webResponse = (WebResponse)httpRequest.GetResponse();
        StreamReader webResponseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
        return webResponseStream.ReadToEnd();
    }

【问题讨论】:

  • 不确定 Lymbix,但您需要向他们发送某种凭据吗? 401 错误会非常清楚地指出这一点。

标签: asp.net sentiment-analysis


【解决方案1】:

表示你没有被授权,所以你需要提供credentials

HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Credentials = new NetworkCredential("username","password");
httpRequest.UseDefaultCredentials = false; //the default is false, but I included it here just to illustrate that it needs to be false in order to use the specified credentials

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多