简体   繁体   中英

Unable to encode my JSON object inside my WebClient UploadString using Headers[“Content-Type”] = “application/x-www-form-urlencoded”

I am working on an ASP.Net MVC 4 web application and I need to post a JSON object to a 3rd part API. Now I need my JSON data to be encoded by setting the content type to be application/x-www-form-urlencoded as mentioned inside the API documentations. so I tried the following by specifying the Content-Type as wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; :

var data = JsonConvert.SerializeObject(mainresourceinfo); 
using (WebClient wc = new WebClient()) 
{
    string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
    Uri uri = new Uri(url);

    //  wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

    crudoutput = wc.UploadString(uri, "INPUT_DATA=" + data);
}

but still the data is not being encoded .. and if I send a value such as 123%456 inside my JSON string, it will be saved as 123E6t inside the 3rd part system. now as a workaround i have manually encoded the JSON object using WebUtility.UrlEncode(data) before sending it to the 3rd part API, and I can see that the values such as 123%456 will be saved correctly ... but I do not want to be manually encoding the data ,, I want to set the content type to specify the encoding ...is this possible?

Use

wc.Headers["Content-Type"] = "application/json"

and try to set charset

wc.Encoding = Encoding.UTF8;
crudoutput = wc.UploadString(uri, "INPUT_DATA=" + Encoding.UTF8.GetString(data));

Charset is specifying the character encoding of the document. Default charset for HTTP 1.1 is ANSI because ANSI is identical to ISO-8859-1 .
Alse WebClient.Encoding by default is set to Encoding.Default that means you get ANSI code page. All Default encodings lose data, so, you might use UTF-8 instead.

So, if you set charset it does not mean that all content have to be encoded as Unicode, but it does mean that these documents can only contain characters defined by Unicode. It means you also need to save your content as UTF-8. In that case you can use Encoding.UTF8.GetString()

Try this :

                using (var client = new WebClient())
            {
                string url = "URL";
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;
                string serialisedData = JsonConvert.SerializeObject(data);
                string response = client.UploadString(url, serialisedData);
            }

You can use the WebClient.UploadValues(Uri, NameValueCollection) method. It will automatically do all stuff for you. You don't even need to specify a Content-Type header because it sends Content-Type: application/x-www-form-urlencoded by default.

Here is an example:

var data = JsonConvert.SerializeObject(mainresourceinfo); 
using (WebClient wc = new WebClient()) 
{
    string url = currentURL + "resources?AUTHTOKEN=" + pmtoken;
    Uri uri = new Uri(url);

    var body = new NameValueCollection
    {
        { "INPUT_DATA", data }
    };
    crudoutput = wc.UploadValues(uri, body);
}

This how I impliment my post method

public static string Post(Exchange exchValues, string url)
{
  WebClient wc = new WebClient();
  wc.Encoding = Encoding.UTF8;
  wc.Headers[HttpRequestHeader.ContentType] = "application/json";
  return wc.UploadString(url, "POST", Json.Stringify(exchValues));
}

This sent 123%456 and the data don't convert to 123%456 ,I 'm use ASP.net Web API ,Json.Stringify use .net Json serialization

Also I face same problem when I try to use GET method the password parameter contain % character and the Api keep decode it so 123$45 decode to 123E6 so I just replace % to %25 and it 's work

HttpUtility.UrlDecode("123%456".Replace("%","%25")); 

Here some links help me MSDN , ASCII Encoding Reference

I recently had the same problem with a 3rd party API. It took a while before I found the solution and all the other answers already given here look a lot like the things I've tried and did not work. What worked for me was the UploadDataAsync. In my case special characters (é, ü, ã etc) would cause an error when sending the json string to the API.

using (WebClient client = new WebClient())
{
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    client.Headers.Add(HttpRequestHeader.Accept, "application/json");
    client.UploadDataAsync(new Uri(apiUrl), "POST", Encoding.UTF8.GetBytes(jsonString));
}

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