尝试检索Web响应时出错401

时间:2013-12-01 22:46:20

标签: c# json httpwebresponse http-status-code-401

每当我尝试“POST”并尝试获得响应时,我都会收到“401未经授权的访问异常”。 我正在尝试开发的应用程序是自动文本,以使用TextNow网站提醒我某些事件。

我环顾互联网,发现我应该使用NetworkCredentials来获取回复,但无济于事。我在某处读到,由于C#中的HTTP交互如何工作,它无法识别JSON 401并使用经过身份验证的标头重试。我该如何解决这个问题?

namespace HTTPWebTest
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    private void snd_Click(object sender, EventArgs e)
    {         
        string pnum = number.Text;
        string msg = text.Text;

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("https://www.textnow.com/api/users/[redacted username]/messages"));
        WebResponse response = null;

        NetworkCredential netCredential =
    new NetworkCredential("[redacted username]", "[redacted password]");
        req.Credentials = netCredential;

        req.PreAuthenticate = true;

        req.Method = "GET";
        response = (HttpWebResponse)req.GetResponse(); //error occurs here <<<<<<<<<<<

        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
        req.Referer = "https://www.textnow.com/api/users/[redacted username]/messages";
        req.AllowAutoRedirect = true;
        req.KeepAlive = true;

        req.ContentType = "application/json";

        StringBuilder postData = new StringBuilder();
        postData.Append("%7B%22contact_value%22%3A%22" + pnum + "%22%2C");
        postData.Append("%22contact_type%22%3A2%2C");
        postData.Append("%22message%22%3A%22" + msg + "%22%2C");
        postData.Append("%22read%22%3A1%2C");
        postData.Append("%22message_direction%22%3A2%2C");
        postData.Append("%22message_type%22%3A1%2C");
        postData.Append("%22date%22%3A%22Sat+Nov+30+2013+13%3A20%3A44+GMT-0800+(Pacific+Standard+Time)%22%2C");
        postData.Append("%22from_name%22%3A%22[Redacted]%22%7D");

        StreamWriter sw = new StreamWriter(req.GetRequestStream());
        sw.Write(postData.ToString());

        response = (HttpWebResponse)req.GetResponse();

    }
}
}

1 个答案:

答案 0 :(得分:0)

我忘记了包含服务器所需的几个自定义标头。

例如:

req.Headers.Add("Access-Control-Request-Headers","accept, origin, x_session, content-type");
req.Headers.Add("Access-Control-Request-Method","POST");

的Fiddler:

The Fiddler Logs of the Request