C# 调用api上传数据 (basic Auth )基本身份验证
我们在这里使用的是 HttpWebRequest 进行上传的
///
///url是路径,data是json数据
///
public static void upload(string url, string data, string userName, string passWord) { string Username = userName; string Password = passWord; byte[] bs = Encoding.ASCII.GetBytes(data); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "Post"; request.CookieContainer = new CookieContainer(); request.ContentType = "application/json;"; request.ContentLength = bs.Length; request.Timeout = 1000000; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } //(1)设置请求Credentials CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(userName, passWord)); request.Credentials = credentialCache; //(2)设置Headers Authorization request.Headers.Add("Authorization", "Basic" + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string content = reader.ReadToEnd(); } } }