0
以下是方法。我一直在研究这一段时间,并修改标题值等。它仍然会出现401 Unauthorized Exception,除非我包含内容长度标题,然后会出现另一个错误,说明内容长度标题无效。有没有人有任何想法如何解决这个问题?其他API尝试POST时返回401未授权的异常
我也试过通过HTTPWebRequest来做这件事。
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的
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();
可能你可能需要明确设置一个标题,说明你正在使用基本认证。请参阅http://kristofmattei.be/2013/02/20/webclient-not-sending-credentials-heres-why/ –
您也可以考虑使用restsharp,它大大简化了这类事情。 – Wjdavis5