gpt4 book ai didi

c# - Webclient/HttpWebRequest with Basic Authentication 返回 404 not found for valid URL

转载 作者:IT王子 更新时间:2023-10-29 03:48:49 24 4
gpt4 key购买 nike

编辑:我想回过头来注意到问题根本不在我这边,而是与另一家公司的代码有关。

我正在尝试使用基本身份验证打开一个页面。我不断收到 404 页面未找到错误。我可以将我的 url 复制并粘贴到浏览器中,它工作正常(如果我还没有登录他们的网站,它会弹出一个凭据框,否则它会打开我想要它打开的内容)。我必须到达正确的位置并进行身份验证,因为如果我故意输入错误的用户名/密码,我会得到一个 401(未经过身份验证的错误),如果我在查询字符串中传递一个错误的参数,我会得到一个内部服务器错误 500 .我试过使用 Webclient 和 HttpWebRequest 都导致相同的 404 not found 错误。

使用网络客户端:

string url = "MyValidURLwithQueryString";
WebClient client = new WebClient();
String userName = "myusername";
String passWord = "mypassword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
var result = client.DownloadString(url);
Response.Write(result);

使用 HttpWebRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MyValidURL");
string authInfo = "username:password";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Http.Get;
request.AllowAutoRedirect = true;
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
Response.Write(s);

最佳答案

//BEWARE
//This works ONLY if the server returns 401 first
//The client DOES NOT send credentials on first request
//ONLY after a 401
client.Credentials = new NetworkCredential(userName, passWord); //doesnt work

//So use THIS instead to send credentials RIGHT AWAY
string credentials = Convert.ToBase64String(
Encoding.ASCII.GetBytes(userName + ":" + password));
client.Headers[HttpRequestHeader.Authorization] = string.Format(
"Basic {0}", credentials);

关于c# - Webclient/HttpWebRequest with Basic Authentication 返回 404 not found for valid URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16044313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com