JinYazhou +

C#使用HTTP Basic Authentication认证


        public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
        {
            string result = string.Empty;

            WebRequest request = WebRequest.Create(new Uri(uri));

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                request.Credentials = GetCredentialCache(uri, username, password);
                request.Headers.Add("Authorization", GetAuthorization(username, password));
            }

            if (timeout > 0) request.Timeout = timeout * 1000;

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
            result = sr.ReadToEnd();

            sr.Close();
            stream.Close();

            return result;
        }

        private static CredentialCache GetCredentialCache(string uri, string username, string password)
        {
            CredentialCache credCache = new CredentialCache();
            credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));

            return credCache;
        }

        private static string GetAuthorization(string username, string password)
        {
            string authorization = string.Format("{0}:{1}", username, password);

            return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
        }



调用代码:


string key = "ba48e6667dca8c83";
string secret = "ba2ee8e2ba48e6667dca8c83dab38f4c";
string value = "97385695";
string url = "http://api.target.com/api/v3/dataquery/" + value;
string content = Request_WebRequest(url, 0, Encoding.UTF8, key, secret);
Console.WriteLine(content);
Console.ReadKey();


最新评论