wtuqi
5/6/2020 - 9:09 AM

HttpWebRequest认证

//方法一 BASIC认证
public static string Get(string Url)
{
    //System.GC.Collect();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.Proxy = null;
    request.KeepAlive = false;
    request.Method = "GET";
    string authorization = "guest" + ":" + "guest";
   
    string base64 = Convert.ToBase64String(Encoding.Default.GetBytes(authorization));
    request.Headers.Add("Authorization", "Basic " + base64);
    request.ContentType = "application/json; charset=UTF-8";
    request.AutomaticDecompression = DecompressionMethods.GZip;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream myResponseStream = response.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
    string retString = myStreamReader.ReadToEnd();
    myStreamReader.Close();
    myResponseStream.Close();
  
    if (response != null)
    {
        response.Close();
    }
    if (request != null)
    {
        request.Abort();
    }
    return retString;
}

//方法二 BASIC基本认证
private Func<string, string> GetCount = (m) =>
 {
     string url = m;
     // 创建HttpWebRequest对象
     HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
     // 设置GET调用方法
     httpRequest.Method = "GET";
     // 设置HTTP头Http Basic认证
     string authorization = "guest" + ":" + "guest";
     string base64 = Convert.ToBase64String(Encoding.Default.GetBytes(authorization));
     httpRequest.Headers.Add("Authorization", "Basic " + base64);

     // HttpWebRequest发起调用
     using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
     {
         // StreamReader对象
         StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
         // 返回结果
         string responseString = sr.ReadToEnd();
         return responseString;
     }
 };