[英]httpResponse 401 unauthorized
i want to post the json data to a webservice. 我想将json数据发布到Web服务。
Here is the method: 方法如下:
public static Int32 SaveCashSale(string username, string key, CashSale cashSale)
{
try
{
// Customize URL according to geo location parameters
var url = string.Format(cashSaleUrl, username, key);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string jsonData = new JavaScriptSerializer().Serialize(new
{
activity_date = cashSale.activity_date = DateTime.Now.ToString(),
added_by = cashSale.added_by,
amount_paid = cashSale.amount_paid,
balance = cashSale.balance,
currency = cashSale.currency,
customer = cashSale.customer,
grand_total = cashSale.grand_total,
});
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
catch (Exception)
{
throw;
}
}
The system the following error message: the remote server returned an error (401) unauthorized . 系统出现以下错误信息: 远程服务器未授权返回错误(401) 。
at this line of the code: 在代码的这一行:
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
the url fomrmat is : 网址格式为:
private const string cashSaleUrl = "http://avaris.kwekud.com/api/v1/sales/cashsale/?username={0}&api_key={1}&format=json";
why the error, and how can i solve it ? 为什么会出现错误,我该如何解决?
You should probably add credentials for your request. 您可能应该为您的请求添加凭据。
Something like (just example - this will use default credentials): 诸如此类(仅作为示例-这将使用默认凭据):
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.