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

时间:2013-05-14 01:04:01

标签: c# https httpwebrequest basic-authentication webrequest

我正在尝试使用基本身份验证对https网址进行网络请求。而它不工作! 下面是我的代码,它实际上工作,如果我使用非安全网址与安全网址,我无法弄清楚我做错了什么。工作只是找到非安全,但当使用安全网址时,我得到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();

1 个答案:

答案 0 :(得分:11)

这对我有用:

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