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