Rest API returns 401 unauthorized exception when trying to POST to it

1.8k views Asked by At

Here is the method. I have been working on this for quite a while, and modifying the header values and such. It still comes up with 401 Unauthorized Exception unless I include content-length header and then it will come up with another error saying the content-length header is invalid. Does anyone have any idea how to resolve this?

I have also tried doing this through an HTTPWebRequest.

Webclient Code:

public void postResponse(string supplierid, string token, string geturl, string lineid)
        {
                lineid = lineid.Trim();
                //string postdata = ("{'supplier_id':'"+supplierid+"', 'token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");

            try
            {
                string postdata = ("{'supplier_id':'"+supplierid+"','token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");

                Console.WriteLine(postdata);
                WebClient postWithParamsClient = new WebClient();
                postWithParamsClient.UploadStringCompleted +=
             new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);
                postWithParamsClient.UseDefaultCredentials = true;
                postWithParamsClient.Credentials = new NetworkCredential(supplierid, token);
                postWithParamsClient.Headers.Add("Content-Type", "application/json");

                string headerlength = postdata.Length.ToString();
                //postWithParamsClient.Headers["Content-Length"] = headerlength;
                postWithParamsClient.UploadStringAsync(new Uri(geturl),
                                                       "POST",
                                                       postdata);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }


        }

HTTPWebRequest

                ASCIIEncoding encoding = new ASCIIEncoding();
                Byte[] postBytes = encoding.GetBytes(postdata);
                // used to build entire input
                StringBuilder sb = new StringBuilder();

                // used on each read operation
                byte[] buf = new byte[8192];

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geturl);
                request.Credentials = new NetworkCredential(supplierid, token);
                request.Method = "POST";
                request.ContentLength = postBytes.Length;
                request.ContentType = "application/json";

                Stream postStream = request.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);
                postStream.Close();
1

There are 1 answers

0
Raphael On

You should try to use fiddler to see what you send and compare to what you server need. Check authorization header and the validity of your credentials. I think it's the first thing to do