2013-05-14 99 views
9

我正在嘗試使用基本身份驗證通過https url執行webrequest。它不工作! 下面是我的代碼,它實際上工作,如果我使用一個非安全的網址vs安全的,我不知道我做錯了什麼。工作只是找到不安全的,但是當一個安全的網址被使用,我得到一個401用戶身份驗證錯誤。它可能是某人在服務器上設置錯誤,或者它是我的代碼?c# - 使用https和基本身份驗證的http web請求

有人可以幫助我嗎?

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

很好的代碼似乎罰款進行身份驗證,但直到我看到了網址實在說不出什麼。 – 2013-05-14 01:21:55

+0

您可能需要填充安全連接的憑據。 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.credentials.aspx – JuStDaN 2013-05-14 04:32:24

+1

感謝您的建議傢伙。看起來我的代碼很好。他們在服務器上設置了錯誤,他們最終修復了這些錯誤! – user1096865 2013-05-20 18:00:58

回答

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

nop,這不起作用 – Cheese 2015-09-16 16:07:04

+0

@Cheese什麼是您的執行錯誤信息? – 2015-10-06 20:26:45

+0

@Cheese這對我有用,但是我不得不添加webRequest.ContentLength = 0,因爲即使主體內容爲0,它也不開心。 – John 2015-11-09 14:57:45