I’m working with a REST web service that uses basic authentication and returns me an XML string. Here is the method that I use to get the data and return it as an XDocument:
var req = (HttpWebRequest)WebRequest.Create(uri);
String readToEnd;
const string postData = "";
var encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
req.Method = "POST";
req.Timeout = 10000;
req.ContentType = "text/XML";
req.ContentLength = byte1.Length;
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
var newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
try
{
var resp = req.GetResponse();
var answer = resp.GetResponseStream();
var _answer = new StreamReader(answer);
readToEnd = _answer.ReadToEnd();
answer.Close();
}
catch (Exception ex)
{
readToEnd = null;
}
return readToEnd != null ? XDocument.Parse(readToEnd) : null;
Now later on, I’ve manipulated that xml and I’m ready to post it back to another uri. I would think it would be the same code except maybe putting my new XML string inside the variable ‘postData’?
Is this the correct way to post an xml string to a webservice? I’ve looked but cant seem to shed any light on this when basic authorization is being used.
I do the following. The key is that you have to write your data to the request stream before posting. Hope it helps.