程式範例來自 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();
            }

        }
    }      
}

 

arrow
arrow
    創作者介紹
    創作者 痞客興 的頭像
    痞客興

    痞客興的部落格

    痞客興 發表在 痞客邦 留言(0) 人氣()