我想将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,
modified_by = cashSale.modified_by,
price_type = cashSale.price_type,
sub_total = cashSale.sub_total,
total_quantity = cashSale.total_quantity,
workspace = cashSale.workspace,
});
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();
网址格式为:
private const string ashSaleItemUrl = "http://avaris.kwekud.com/api/v1/sales/cashsale/?username={0}&api_key={1}";
我的代码有什么问题,如何解决?