C#HTTP基本身份验证问题

问题描述:

这是我现在的C#代码。

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.upcloud.com/1.2/account");
    string authInfo = "username:password";
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    request.Headers.Add("Authorization", "Basic " + authInfo);
    request.ContentType = "application/json";
    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();
    Console.Write(s);




代码对我来说很好但是我得到这个例外  System.Net.WebException:
基础连接已关闭
 尝试获取响应时( HttpWebResponse response
=(HttpWeb响应)request.GetResponse();
)。

The code looks fine to me but I get this exception System.Net.WebException: The underlying connection was closed when trying to get a response (HttpWebResponse response = (HttpWebResponse)request.GetResponse();).


我正在尝试做的基本上是"翻译"在"UpCloud API入门"页面中报告的python示例(我无法发布链接) 到C#但是无论如何在我做出的许多尝试中,我仍然没有找到解决方案。先谢谢

What I'm trying to do is basically "translate" the python example reported in the "Getting started with UpCloud API" page (i cant post links) to C# but regardless of the many attempts I made I still have not found a solution. Thanks in advance.






代码看起来很合理。你得到的错误意味着远程端关闭了连接,可能是由任何东西造成的,包括服务器断开连接,网络外出等等。一般情况下,如果你发送错误数据然后你会得到
错误回复所以它似乎不太可能与你的数据有关。你可以考虑使用Fiddler或同等的监控电话,看看你发送的请求和你得到的回复。

The code looks reasonable. The error you're getting means the remote end closed the connection and could be caused by any # of things including the server dropping the connection, the network going out, etc. In general if you send bad data then you'll get an error response back so it seems unlikely related to your data. You might consider using Fiddler or equivalent to monitor the call to see what request you're sending and what response you're getting back.

您也可以考虑使用
WebClient

HttpClient
。它们需要更少的代码并处理更多场景。两个链接都提供了您需要的代码,而不是类似的身份验证。

You might also consider using WebClient or HttpClient instead. They require less code and handle more scenarios. Both links provide the code you need, other than the authentication which works similarly.