c# - 使用 https 和基本身份验证的 http web 请求

标签 c# https httpwebrequest basic-authentication webrequest

我正在尝试通过具有基本身份验证的 https url 执行网络请求。而且它不起作用! 下面是我的代码,如果我使用非安全 url 与安全 url,它实际上可以工作,而且我无法弄清楚我做错了什么。工作只是找到非安全的,但是当使用安全的 url 时,我收到 401 用户身份验证错误。可能是有人在服务器上设置错误,还是我的代码?

有人可以帮我吗?

        var req = System.Net.HttpWebRequest.Create(Url) as HttpWebRequest;
        req.Method = Method.ToString();
        req.ContentType = "application/json";
        req.Date = RequestTime;
        req.Proxy = null;
        string credentials = String.Format("{0}:{1}", "xxxx", "xxxx");
        byte[] bytes = Encoding.ASCII.GetBytes(credentials);
        string base64 = Convert.ToBase64String(bytes);
        string authorization = String.Concat("Basic ", base64);
        req.Headers.Add("Authorization", authorization);
        HttpWebResponse response = (HttpWebResponse)req.GetResponse();
    Stream receiveStream = response.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
        string responsebody = readStream.ReadToEnd();
        Console.WriteLine(responsebody);

        response.Close();
        readStream.Close();

最佳答案

这对我有用:

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.ContentLength = 0; // added per comment
string autorization = "username" + ":" + "Password";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("AUTHORIZATION", autorization);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}",webResponse.Headers);
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
    string s = reader.ReadToEnd();
    Console.WriteLine(s);
    reader.Close();
}

关于c# - 使用 https 和基本身份验证的 http web 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533552/

相关文章:

c# - 如何在控件中按 Tab 键顺序查找第一个控件?

c# - 生成特定文本文件的类的重构策略

c# - 如何在字符串中出现第三个空格时分割字符串?

java - "IllegalArgumentException: SSLSocketFactory is null"在某些设备上,有些不是?

java - JSF 2 上的 HTTPS,用于 protected 资源和登录

c++ - gSOAP - soap_ssl_client_context() 的参数

c# - 如何在 HttpWebRequest POST 中将对象作为参数传递?

json - PowerShell 调用-WebRequest | API调用

c# - 使用 System.Runtime.Caching,但是当我去检索它时,它是空的?

c# - Web 请求错误 407 需要代理身份验证