HTTP 401 Error sending XML in REST

I am trying to send XML to a REST service. Here is the code I'm using:

I get the following error when calling a service.

The remote server returned an error: (401) Unauthorized.

I also tried setting NetworkCredentials directly ie

NetworkCredential nc = new NetworkCredential(username, password); serviceRequest.Credentials = nc; 

Thank you for your help.

 Uri address = new Uri("https://localhost:30000/restservice/"); // Create the web request HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; // Set type to POST request.Method = "POST"; request.ContentType = "application/json"; string data = @"<Sample XML Here>"; // Create a byte array of the data we want to send byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); // Set the content length in the request headers request.ContentLength = byteData.Length; // Write data using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } string usernamePassword = username + ":" + password; CredentialCache mycache = new CredentialCache(); mycache.Add(address, "Basic", new NetworkCredential(username, password)); request.Credentials = mycache; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output Response.Write(reader.ReadToEnd()); } 
+4
source share
3 answers

Use Fiddler and see the WWW-Authenticate header that is returned from the server. This will tell you which authentication scheme the server supports.

0
source

A few things to try:

  • Change the content type as you are not sending json to it
  • Do not encode data as pending xml, not binary stream

Hope this helps.

0
source

try setting credentials in the request as follows

 request.Credentials = new NetworkCredential(username, password); 
0
source

Source: https://habr.com/ru/post/1336042/


All Articles