Search code examples
c#.nethttp-post

Desktop app error 401 How can I send the data


I do not have a problem getting tokens in the desktop application I developed, but when I try to send data, I get a 401 error.

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();         
        }
}

Solution

  • Post to api with c # windows form application. 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);
    
                };