• C# 请求API(一次登陆,多次请求)


     1 // User Session & cookie
     2     public class APISession
     3     {
     4         private string cookie;
     5 
     6         public string Cookie
     7         {
     8             get {  return cookie; }
     9 
    10             set {  cookie = value;}
    11         }
    12 
    13         private string session;
    14 
    15         public string Session
    16         {
    17             get {  return session;}
    18 
    19             set {  session = value;}
    20         }
    21 
    22         private DateTime expiretime;
    23 
    24         public DateTime Expiretime
    25         {
    26             get {  return expiretime;}
    27 
    28             set {  expiretime = value;}
    29         }
    30 
    31         private string url = System.Configuration.ConfigurationSettings.AppSettings["QCServer"]; // domain url
    32 
    33         public string Url
    34         {
    35             get { return url;}
    36 
    37             set { url = value;}
    38         }            
    39     }
     1 //请求对象 
     2 public class Requester
     3     {
     4         private string username;
     5 
     6         public string Username
     7         {
     8             get { return username; }
     9             set { username = value; }
    10         }
    11         private string password;
    12 
    13         public string Password
    14         {
    15             get { return password; }
    16             set { password = value; }
    17         }
    18         bool isauthforQC = false;
    19 
    20         public bool IsauthforQC
    21         {
    22             get { return isauthforQC; }
    23             set { isauthforQC = value; }
    24         }
    25         private APISession qs = new APISession();
    26 
    27         public APISession Qs
    28         {
    29             get { return qs; }
    30             set { qs = value; }
    31         }
    32 
    33         private Connection _instance;
    34 
    35         public Connection Instance
    36         {
    37             get { return _instance; }
    38             set { _instance = value; }
    39         }
    40 
    41     }
    
    
      1   public class Connection
      2     {
      3         //实例化Connection对象
      4         public static Connection GetInstance(Requester reqer)
      5         {
      6             Connection instance = null;
      7             if (!reqer.IsauthforQC)
      8             {
      9                 instance = new Connection();
     10                 reqer.Instance = instance;
     11             }
     12             else
     13             {
     14                 instance = reqer.Instance;
     15             }
     16             return instance;
     17         }
     18 
     19         /// <summary>
     20         /// 通过初始化,进行登陆授权并保存Cookie 和Session到请求对象中,下次使用
     21         /// </summary>
     22         /// <param name="reqer"></param>
     23         /// <returns></returns>
     24         public bool initConnection(Requester reqer)
     25         {
     26             string url = reqer.Qs.Url + @"/qcbin/authentication-point/authenticate";// 校验登陆成功,并返回Cookie 
     27             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
     28             request.Method = "Get";
     29             request.ContentType = "application/xml";
     30 
     31             string authInfo = reqer.Username.Trim() + ":" + reqer.Password.Trim();
     32             authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
     33             request.Headers[HttpRequestHeader.Authorization] = "Basic " + authInfo;
     34             try
     35             {
     36                 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
     37                 { 
     38                     string StrCookie = response.Headers.ToString();
     39                     string StrCookie1 = StrCookie.Substring(StrCookie.IndexOf("LWSSO_COOKIE_KEY=") + 17);// 截取Cookie 
     40                     StrCookie1 = StrCookie1.Substring(0, StrCookie1.IndexOf(";"));
     41                     reqer.Qs.Cookie = StrCookie1; // 保存Cookie 到requester 对象
     42                     StreamReader reader = new StreamReader(response.GetResponseStream());
     43                     string result = reader.ReadToEnd().ToString();
     44                     Uri target = new Uri(reqer.Qs.Url);
     45                     HttpWebRequest myWebRequest1 = (HttpWebRequest)WebRequest.Create(reqer.Qs.Url + @"/qcbin/rest/site-session");// 校验登陆成功,并返回Session
     46                     myWebRequest1.Method = "Post";
     47                     myWebRequest1.ContentType = "text/xml";
     48                     myWebRequest1.CookieContainer = new CookieContainer();
     49                     myWebRequest1.CookieContainer.Add(new Cookie("LWSSO_COOKIE_KEY", StrCookie1) {Domain = target.Host });// 添加Cookie 到本次请求
     50                     WebResponse webResponse1 = myWebRequest1.GetResponse();
     51                     string strCookie2 = webResponse1.Headers.ToString();
     52                     strCookie2 = strCookie2.Substring(strCookie2.IndexOf("QCSession=")+ 10);// 截取Session
     53                     strCookie2 = strCookie2.Substring(0, strCookie2.IndexOf(";"));
     54                     reqer.Qs.Session = strCookie2;// 保存Session到requester 对象
     55                     reqer.Qs.Expiretime = DateTime.Now.AddMinutes(2);//设定请求有效期
     56                 }
     57             }
     58             catch (Exception e)
     59             {
     60                                 
     61                 return false;
     62             }
     63             reqer.IsauthforQC = true;// 授权成功 
     64             return true;
     65 
     66         }
     67         /// <summary>
     68         /// 通过Get 请求获取API信息
     69         /// </summary>
     70         /// <param name="reqer">请求对象</param>
     71         /// <param name="queryURL">请求具体API方法</param>
     72         /// <param name="requesttype">请求类型(GET,Post..)</param>
     73         /// <param name="accepttype">接受类型(application/json..)</param>
     74         /// <returns></returns>
     75         public string SendRequest(Requester reqer, string queryURL, string requesttype, string accepttype)
     76         {
     77             bool isauth = false;
     78             string result = string.Empty;
     79 
     80             if (!reqer.IsauthforQC)
     81             {
     82                 isauth = initConnection(reqer);
     83             }
     84             else
     85             {
     86                 isauth = true;
     87             }
     88 
     89             if (isauth)
     90             {
     91                 HttpWebRequest myWebRequest2 = (HttpWebRequest)WebRequest.Create(reqer.Qs.Url + queryURL);
     92                 myWebRequest2.Method = requesttype;
     93                 myWebRequest2.ContentType = "application/json";
     94                 myWebRequest2.Accept = accepttype;
     95                 myWebRequest2.CookieContainer = new CookieContainer();
     96                 Uri target = new Uri(reqer.Qs.Url);
     97                 myWebRequest2.CookieContainer.Add(new Cookie("LWSSO_COOKIE_KEY", reqer.Qs.Cookie) { Domain = target.Host });// 添加Cookie 到本次请求
     98                 myWebRequest2.CookieContainer.Add(new Cookie("QCSession", reqer.Qs.Session) { Domain = target.Host });// 添加Session 到本次请求
     99                 try
    100                 {
    101                     WebResponse webResponse2 = myWebRequest2.GetResponse();
    102                     StreamReader reader2 = new StreamReader(webResponse2.GetResponseStream());
    103                     result = reader2.ReadToEnd().ToString();//获取结果
    104                 }
    105                 catch (Exception e)
    106                 {
    107 
    108                     result = "";
    109                 }
    110             }
    111             return result;
    112         }
    113         /// <summary>
    114         /// 通过PUT请求修改对象信息
    115         /// </summary>
    116         /// <param name="reqer"></param>
    117         /// <param name="updateValue"></param>
    118         /// <param name="requesttype"></param>
    119         /// <param name="accepttype"></param>
    120         /// <param name="domain"></param>
    121         /// <returns></returns>
    122         public string PUTRequest(Requester reqer, string updateValue, string requesttype, string accepttype, string domain)
    123         {
    124             bool isauth = false;
    125             string result = "";
    126             int columnsize = 385;     // the field column is varchar(255) in DB
    127             if (!reqer.IsauthforQC)
    128             {
    129                 isauth = initConnection(reqer);
    130             }
    131             else
    132             {
    133                 isauth = true;
    134             }
    135             if (isauth)
    136             {
    137                 try
    138                 {
    139                     HttpWebRequest myWebRequest2;
    140                  
    141                     // get the current value
    142                     string url = "URL";//需要访问的方法
    143                     var projectstr = SendRequest(reqer, url, "Get", "application/json");// 获取返回结果
    144 
    145                     JObject Fields = (JObject)JsonConvert.DeserializeObject(projectstr);
    146                     StringBuilder currentValue = new StringBuilder();
    147                     
    148                     // 获取需要修改对象属性值
    149                     JArray fld = (JArray)Fields["Fields"];
    150                     foreach (JObject item in fld)
    151                     {
    152                         if (item["Name"].ToString().Equals("user-template-13"))
    153                         {
    154                             try
    155                             {
    156                                 // append the existing value
    157                                 currentValue.Append(item["values"][0]["value"].ToString());
    158                             }
    159                             catch (Exception)
    160                             {
    161                             }
    162                         }
    163                     }
    164                     // append the new value
    165                     currentValue.Append(updateValue);//在原值后面增加新值
    166                      
    167                     myWebRequest2 = (HttpWebRequest)WebRequest.Create(reqer.Qs.Url + "url1");//访问更新的方法
    168 
    169                     myWebRequest2.Method = "PUT";
    170                     myWebRequest2.ContentType = "application/xml";
    171                     myWebRequest2.Accept = "application/xml";
    172                     myWebRequest2.CookieContainer = new CookieContainer();
    173                     Uri target = new Uri(reqer.Qs.Url);
    174                     myWebRequest2.CookieContainer.Add(new Cookie("LWSSO_COOKIE_KEY", reqer.Qs.Cookie) { Domain = target.Host });
    175                     myWebRequest2.CookieContainer.Add(new Cookie("QCSession", reqer.Qs.Session) { Domain = target.Host });
    176 
    177                     // xml 对象
    178                     XDocument postDoc = new XDocument(
    179                             new XElement("Entity", new XAttribute("Type", "test"),
    180                             new XElement("Fields",
    181                             new XElement("Field", new XAttribute("Name", "user-template-13"), new XElement("Value", currentValue.ToString())))));
    182                     // xml 对象
    183 
    184                     var bytes = Encoding.ASCII.GetBytes(postDoc.ToString());
    185                     Stream requestStream = myWebRequest2.GetRequestStream();
    186 
    187                     // the field column is varchar(255) in DB
    188                     if (bytes.Length > columnsize)
    189                     {
    190                         return "Limit";
    191                     }
    192                     requestStream.Write(bytes, 0, bytes.Length);
    193                     requestStream.Close();
    194 
    195                     HttpWebResponse res = (HttpWebResponse)myWebRequest2.GetResponse();
    196                     if (res.StatusCode == HttpStatusCode.OK)
    197                     {
    198                         result = "Success";
    199                     }
    200                     else
    201                     {
    202                         result = "Fail";
    203                     }
    204                 } 
    205                 catch (WebException ex)
    206                 {
    207                     result = "Fail";
    208                     throw ex;
    209                 }
    210                 catch (Exception ex)
    211                 {
    212                     result = "Fail";
    213                     throw ex;
    214                 }
    215             }
    216             return result;
    217         }
    218     }
    
    
    
     
  • 相关阅读:
    js 去除金额的千位分隔符
    vue中的iviewUI导出1W条列表数据每次只导出2000条的逻辑
    js取整数、取余数的方法
    http协议
    vue 项目安装sass的依赖包
    浅析vue的双向数据绑定
    闭包
    Top 20 NuGet packages for captcha
    IIS URL Rewrite Module的防盗链规则设置
    IIS URL Rewrite – Installation and Use
  • 原文地址:https://www.cnblogs.com/allenzhang/p/11227027.html
Copyright © 2020-2023  润新知