我想将json数据发布到web服务。
以下是方法:
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;
}
}
系统出现以下错误消息: 远程服务器返回错误(401)未经授权。
在这行代码中:
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
url fomrmat是:
private const string cashSaleUrl = "http://avaris.kwekud.com/api/v1/sales/cashsale/?username={0}&api_key={1}&format=json";
为什么会出错,我该如何解决?
答案 0 :(得分:2)
您应该为您的请求添加凭据。
类似的东西(只是示例 - 这将使用默认凭据):
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;