2017-08-08 52 views
0

我在django rest框架中給了我一個休息服務。我正在嘗試在C#中使用此服務。獲取web服務返回的實際錯誤代碼

這裏是我的示例代碼:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://abcd.zyz.com/hello/pqr"); 

request.Method = "POST"; 
request.ContentType = "application/json"; 

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 

string data = "{" + "\"key" + "\":" + "\"" + value + "\"}"; 


byte[] bytes = encoding.GetBytes(data); 

request.ContentLength = bytes.Length; 

string strUserNameAndPasswordForHeader = strUserName + ":" + strPassword; 

request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(strUserNameAndPasswordForHeader)); /*Add username password to header*/ 

using (Stream requestStream = request.GetRequestStream()) 
{ 
    // Send the data. 
    requestStream.Write(bytes, 0, bytes.Length); 
} 

var response = request.GetResponse(); 

最後一行導致網絡異常。當我嘗試獲得狀態碼時,我得到了403禁止。編寫該服務的用戶說密碼不正確時返回-5。當用戶帳戶不存在時返回-6。我如何處理這些錯誤值,因爲對於我來說,對於這些場景中的每一個,它總是返回403.我在哪裏可以看到web異常中的-5和-6?

回答

1

當調用HttpWebRequest.GetResponse時,不成功的HTTP響應(因此2xx以外的狀態碼)將拋出WebException。爲了仍然可以訪問的響應,可以捕獲該異常,然後訪問其Response屬性仍然可以訪問到從服務器接收到的WebResponse對象:

try 
{ 
    var response = request.GetResponse(); 
    // handle successful case 
} 
catch (WebException ex) 
{ 
    if (ex.Response != null) 
    { 
     var responseStream = ex.Response.GetResponseStream(); 
     // do something with the response 
    } 
    else 
     throw; 
} 
+0

爲什麼downvote ...? – poke