2014-02-23 226 views
-1

我想發佈json數據到web服務。httpResponse 401未授權

這裏是方法:

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

你有某種授權?也許在web.config? –

+0

@PatrickHofman不,它是一個Windows應用程序。所以沒有web配置文件。 – Djama

+0

一個web.config用於web服務器(因此命名爲'web') –

回答

2

您應該爲您的請求添加憑據。

喜歡的東西(例如剛 - 這將使用默認憑證):

httpWebRequest.UseDefaultCredentials = true; 
httpWebRequest.PreAuthenticate = true; 
httpWebRequest.Credentials = CredentialCache.DefaultCredentials; 
+0

我加了它但仍然給我同樣的錯誤:遠程服務器返回一個錯誤:(401)未經授權。 – Djama

+0

我試圖看看API。似乎它也需要URL中的&format = json。請補充一點。 – SimonGA

+0

我增加了它,但同樣的錯誤,我不知道可能是什麼問題。 – Djama