0

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

1 Answer 1

1

You haven't written the post data to the request stream. You will need to call datastream.Write before you call GetResponse.

For example:

var buffer = Encoding.UTF8.GetBytes(strPostData);
r.ContentLength = buffer.Length;
datastream.Write(buffer, 0, buffer.Length);
datastream.Close();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.