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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16533552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:15:10  来源:igfitidea点击:

c# - http web request with https and basic authentication

c#httpshttpwebrequestbasic-authenticationwebrequest

提问by user1096865

I'm trying to do a webrequest over a https url with basic authentication. And its not working! below is my code, it actually works if i use a non secure url vs the secure one, and i can't figure out what i'm doing wrong. Works just find with non secure, but when a secure url is used, i get a 401 user auth error. Could it be someone set up wrong on the server, or is it my code?

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

Could someone help me?

有人可以帮助我吗?

        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();

回答by Herbert Yu

This works for me:

这对我有用:

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();
}