I have a unique request for me, where I need to send a JSON POST request but read a XML GET. I have tried this below, but I get an error of
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
What do I alter in order for my XML GET to succesful be able to read the response?
public bool PerformPost(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
string strEndpointURL = string.Format("websitegoeshere");
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string strPostData = "";
foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
strPostData += "hs_context=";
HttpWebRequest r = (System.Net.HttpWebRequest)WebRequest.Create(strEndpointURL);
r.Method = "POST";
r.Accept = "application/json";
r.ContentType = "application/x-www-form-urlencoded";
r.ContentLength = strPostData.Length;
r.KeepAlive = false;
Stream datastream = r.GetRequestStream();
WebResponse response = r.GetResponse();
datastream = response.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
string responsefromserver = reader.ReadToEnd();
var xml = System.Xml.Linq.XElement.Parse(responsefromserver);
if (xml.Elements("sid").FirstOrDefault().Value == "1") { return true; }
else
{
var errors = xml.Elements("fail");
foreach (var error in errors.Elements("fail"))
{
strMessage = error.Value;
return false;
}
}
reader.Close();
datastream.Close();
response.Close();
return true;
}