10

我正在尝试通过具有基本身份验证的 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();
4

1 回答 1

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();
}
于 2014-04-03T18:39:01.603 回答