Question

Whenever I try a "POST" and attempt to get a response, I get a "401 unauthorized access exception". The application I am trying to develop is automated Texts to remind me of certain events using the TextNow website.

I have looked around the internet and found that I should use NetworkCredentials to allow me to grab a response, but to no avail. I read around somewhere that because of how HTTP interaction in C# works, that it can't recognize a JSON 401 and retry with an authenticated header. How do I fix this?

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();

    }
}
}
Was it helpful?

Solution

I had forgotten to include several custom headers that the server required.

For Example:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top