c# 使用http摘要认证

2021-06-15 04:03

阅读:392

标签:bsp   iges   使用   add   cep   using   result   exception   content   

.net 使用http摘要认证,返回json数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String outMsg="";

          String result=  Request("url",
                "GET", "", "", out outMsg);

          Console.WriteLine(result);

          Console.WriteLine(outMsg);

          Console.ReadKey();
        }

        public static string Request(string sUrl, string sMethod, string sEntity, string sContentType,
    out string sMessage)
        {
            try
            {
                sMessage = "";
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    client.Credentials = CreateAuthenticateValue(sUrl);

                    WebHeaderCollection customerHeader= new WebHeaderCollection();
                    customerHeader.Add(HttpRequestHeader.Accept, "application/json");
                    customerHeader.Add(HttpRequestHeader.ContentType, "application/json;charset=UTF-8");

                    client.Headers = customerHeader;

                    Uri url = new Uri(sUrl);
                    byte[] bytes = Encoding.UTF8.GetBytes(sEntity);
                    byte[] buffer;
                    switch (sMethod.ToUpper())
                    {
                        case "GET":
                            buffer = client.DownloadData(url);
                            break;
                        case "POST":
                            buffer = client.UploadData(url, "POST", bytes);
                            break;
                        default:
                            buffer = client.UploadData(url, "POST", bytes);
                            break;
                    }

                    return Encoding.UTF8.GetString(buffer);
                }
            }
            catch (WebException ex)
            {
                sMessage = ex.Message;
                var rsp = ex.Response as HttpWebResponse;
                var httpStatusCode = rsp.StatusCode;
                var authenticate = rsp.Headers.Get("WWW-Authenticate");

                return "";
            }
            catch (Exception ex)
            {
                sMessage = ex.Message;
                return "";
            }
        }

        private static CredentialCache CreateAuthenticateValue(string sUrl)
        {
            CredentialCache credentialCache = new CredentialCache();
            credentialCache.Add(new Uri(sUrl), "Digest", new NetworkCredential("admin", "password"));

            return credentialCache;
        }  
    }
}

 

c# 使用http摘要认证

标签:bsp   iges   使用   add   cep   using   result   exception   content   

原文地址:https://www.cnblogs.com/wenming205/p/10387159.html


评论


亲,登录后才可以留言!