向REST服务发送请求时发生C#401错误
本文关键字:C#401 错误 REST 服务 请求 | 更新日期: 2023-09-27 17:58:32
我正在尝试发送http请求以请求REST服务。然而,我一直收到401错误。我在http头中包含了一个基本的授权信息,但它仍然收到了相同的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");
}
尝试添加这两行:
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";