[英]Rest API returns 401 unauthorized exception when trying to POST to it
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. 除非我包含content-length标头,否则它仍然会显示401 Unauthorized Exception,然后它将出现另一个错误,指出content-length标头无效。 Does anyone have any idea how to resolve this? 有谁知道如何解决这个问题?
I have also tried doing this through an HTTPWebRequest. 我也尝试通过HTTPWebRequest进行此操作。
Webclient Code: Web客户端代码:
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 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();
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 我认为这是第一件事
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.