2014-04-15 127 views
0

我正在嘗試發送http請求以請求REST服務。但是,我不斷收到401錯誤。我在http頭中包含了一個基本的授權信息,但它仍然收到了相同的401錯誤。任何人都可以幫我檢查一下我的代碼嗎?由於向REST服務發送請求時出現C#401錯誤

public void getAuth(string reqUrl) 
    { 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUrl); 
     string userinfo = "test:test"; 
     byte[] byteUserInfo = Encoding.ASCII.GetBytes(userinfo); 
     string code = Convert.ToBase64String(byteUserInfo); 
     req.Headers.Add("Authorization", "Basic " + code); 
     req.Method = "get"; 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.Credentials = CredentialCache.DefaultCredentials; 
     HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 
     Console.WriteLine(response); 
    } 

    static void Main(string[] args) 
    { 
     Tester2 test = new Tester2(); 
     test.getAuth("http://MyHost/wiki/rest/prototype/1/search/site?query=property"); 
    } 

回答

0

嘗試增加兩行:

req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10"; 
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,* /*;q=0.8"; 
+0

嗨lgoy,感謝您的回答。我試過了,它返回了一個400錯誤(錯誤的請求)。我檢查了相關REST服務的開發人員手冊,它提到了「使用包含'基本用戶名:密碼'的HTTP基本認證(授權HTTP頭部),但是請注意,用戶名:密碼必須是base64編碼的,URL還必須包含'os_authType =基本'查詢參數「。我認爲401錯誤的發生可能是因爲我沒有在我的URL中插入'os_authType = basic'。但是,他們沒有提供關於在哪裏插入此參數的進一步說明。 – Sid

相關問題