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