2015-07-01 63 views
9

我的工作耗費了REST API,我使用其中的密碼編碼爲Base64基本身份驗證如下如何捕獲請求後由REST API發送的響應令牌?

private XmlDocument sendXMLRequest(string requestXml) 
    { 
     string destinationUrl = "https://serviceapi.testgroup.com/testtp/query"; 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl); 
     request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("API_TEST_NR:Testnol1$")); 
     byte[] bytes; 
     bytes = System.Text.Encoding.ASCII.GetBytes(requestXml); 
     request.Method = "POST"; 

     request.ContentLength = bytes.Length; 
     //request.Connection = "keep-alive"; 
     request.ContentType = "text/xml"; 
     request.KeepAlive = true; 
     request.Timeout = 2000; 
     request.MediaType = "text/xml"; 
     Stream requestStream = request.GetRequestStream(); 
     requestStream.Write(bytes, 0, bytes.Length); 
     requestStream.Close(); 
     HttpWebResponse response; 
     Stream responseStream; 

     using (response = (HttpWebResponse)request.GetResponse()) 
     { 
      if (response.StatusCode == HttpStatusCode.OK) 
      { 
       responseStream = response.GetResponseStream(); 
       XmlReader reader = new XmlTextReader(responseStream); 

       XmlDocument xmlDoc = new XmlDocument(); 
       xmlDoc.Load(reader); 


       try { reader.Close(); } 
       catch { } 
       try { responseStream.Close(); } 
       catch { } 
       try { response.Close(); } 
       catch { } 
       return xmlDoc; 
      } 
     } 
     try { response.Close(); } 
     catch { } 
     return null; 
    } 

我有點新的網頁API的工作,我知道,API與響應基於API文檔成功授權後訪問x-token,我不確定如何從HTTP頭訪問或捕獲它。

我可以知道一個好辦法嗎?

回答

4

這比我以爲只是用它的名字捕獲容易。

string xtoken= response.Headers["custom-header"]; 
Console.WriteLine(xtoken); 
4

請嘗試以下代碼,請求數據使用WebRequest類。在大多數情況下,WebRequest類足以接收數據。但是,如果您需要設置協議特定的屬性,則必須將WebRequest強制轉換爲協議特定的類型。例如,要訪問HttpWebRequest的HTTP特定屬性,請將WebRequest強制轉換爲HttpWebRequest引用。

private XmlDocument GetRootLevelServiceDocument(
string serviceEndPoint, string oAuthToken) 
{ 
XmlDocument xmlDoc = new XmlDocument(); 
HttpWebRequest request = CreateHttpRequest(serviceEndPoint, 
    oAuthToken); 

using (HttpWebResponse response = 
    (HttpWebResponse)request.GetResponse()) 
{ 
    using (XmlReader reader = 
     XmlReader.Create(response.GetResponseStream(), 
     new XmlReaderSettings() { CloseInput = true })) 
    { 
     xmlDoc.Load(reader); 

     string data = ReadResponse(response); 
     if (response.StatusCode != HttpStatusCode.OK) 
     { 
      LogMsg(string.Format("Error: {0}", data)); 
      LogMsg(string.Format(
       "Unexpected status code returned: {0}", 
       response.StatusCode)); 
     } 
    } 
} 

return xmlDoc; 
} 
+0

我已經得到了我的答案。謝謝!! – DoIt

+0

OP爲什麼要「嘗試這個」?一個好的答案將總是解釋做了什麼以及爲什麼這樣做,不僅是爲了OP,而且是爲了將來SO的訪問者。 –

相關問題