2014-02-23 3 views
-1

json 데이터를 웹 서비스에 게시하려고합니다. 여기 httpResponse 401 unconthorized

메소드이다

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 응용 프로그램입니다. 그래서 웹 설정 파일이 없습니다. – Djama

+0

web.config는 웹 서버 (그러므로'web'라는 이름)입니다. –

답변

2

요청에 대한 자격 증명을 추가해야합니다. 같은

뭔가 (단지 예 -이 기본 자격 증명을 사용합니다) :

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

나에게 동일한 오류가 발생했습니다 : 원격 서버가 오류를 반환했습니다 : (401) Unauthorized. – Djama

+0

API를 살펴 보았습니다. URL에 & format = json도 필요합니다. 그것을 추가하십시오. – SimonGA

+0

나는 그것을 추가했지만 같은 오류가, 나는 문제가 될 수 있습니다 궁금해. – Djama