程式範例來自 http://stackoverflow.com/questions/16533552/c-sharp-http-web-request-with-https-and-basic-authentication
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace GetUrlInformation
{
class Program
{
static void Main(string[] args)
{
string url = @"http://YourServerIpOrHostName/WebPath";
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();
}
}
}
}
留言列表