简体   繁体   中英

Http Post Fails when Trying to Post JSON Data that contains XML

I'm trying to do an http post with the following function. It works fine with my post data contains normal JSON data (just text). But now my json data also contains xml in one of it's fields.

 public string postJSON(string username, string password, string endPoint, string json)
    {
        HttpWebRequest request = CreateWebRequest(endPoint, "POST", "text/json");
        request.Credentials = new NetworkCredential(username, password);
        try
        {
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    return result;
                }
            }
        }
        catch (Exception ex)
        {
            logger.WriteToLog("RequestMaker", "postJason function: " + ex.Message);
            return "error";
        }          
    }

But I'm getting a bad url error (400) when I try to do so. My endpoint URL looks something like this: http://se.api.anpdm.com/v1/import/mailinglist/#####/demographicmapping/### And a sample Json code that has to posted looks like this.

"{\"XMLData\":\"<Subscribers><Subscriber><Name>Pedram</Name><Email>mobedi@live.com</Email><DemographicData><Demographic mapTo='Urval'>30</Demographic></DemographicData></Subscriber><Subscriber><Name>Anders Svensson</Name><Email>pmobedi@yahoo.com</Email><DemographicData><Demographic mapTo='Urval'>27</Demographic></DemographicData></Subscriber></Subscribers>\"}"

Is there something else I should do?

If you are using Framework 4.0., this can be because of your web server validation configuration settings, which denies to send xml or other tags in the body of your requests. If it is so, try to change your RequestValidationMode to 2.0 in your web section of web.config:

    <httpRuntime requestValidationMode="2.0" />

I got the answer, Small stupid things: “XMLData” is wrong. It should be “XmlData” exactly as the Json parameter written in the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM