c# desktop app error 401 如何发送数据

c # desktop app error 401 How can I send the data

我在我开发的桌面应用程序中获取令牌没有问题。但是当我尝试发送数据时,出现 401 错误。

HttpWebRequest webRequest;
string requestParams = "";
webRequest = (HttpWebRequest)WebRequest.Create("url");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("x-api-key", "112233");
webRequest.Headers.Add("AccessToken", token);
byte[] byteArray = Encoding.UTF8.GetBytes(req);
webRequest.ContentLength = byteArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
     requestStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = webRequest.GetResponse()) 
{
    using (Stream responseStream = response.GetResponseStream())
        {
             StreamReader rdr = new StreamReader(responseStream, Encoding.UTF8);
             string Json = rdr.ReadToEnd();         
        }
}

问题是关于设置令牌的。首先,您需要确定您的服务器想要什么作为令牌。您可以尝试使用 Bearer 令牌。

    webRequest.Headers.Add("Authorization", "Bearer " + token);

要让您的程序运行,您必须提供实际的 URL,而不仅仅是字符串 "url",在

webRequest = (HttpWebRequest)WebRequest.Create("url");

Post到api用c#windows窗体应用。 oauth2.0

            using (var client1 = new HttpClient ())
            {
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token());
                client1.DefaultRequestHeaders.Add("x-api-key", "xxxx");

                var builder = new UriBuilder(new Uri("you - url"));

                HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, builder.Uri);

                request1.Content = new StringContent("{\"values\":" + JsonConvert.SerializeObject("you -data")+ "}", Encoding.UTF8, "application/json");
               
                HttpResponseMessage response = await client1.SendAsync(request1);

            };