简体   繁体   English

无法使用 Headers[“Content-Type”] = “application/x-www-form-urlencoded” 在我的 WebClient UploadString 中编码我的 JSON 对象

[英]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.我正在开发 ASP.Net MVC 4 Web 应用程序,我需要将 JSON 对象发布到第三部分 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.现在我需要通过将内容类型设置为application/x-www-form-urlencoded来编码我的 JSON 数据,如 API 文档中所述。 so I tried the following by specifying the Content-Type as wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";所以我通过将Content-Type指定为wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";来尝试以下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.但仍然没有对数据进行编码..如果我在我的 JSON 字符串中发送一个诸如123%456的值,它将在第三部分系统中保存为123E6t 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?现在作为一种解决方法,我在将 JSON 对象发送到第 3 部分 API 之前使用WebUtility.UrlEncode(data)对其进行了手动编码,我可以看到123%456等值将被正确保存......但我没有想要手动编码数据,我想设置内容类型以指定编码......这可能吗?

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. Charset指定文档的字符编码。 Default charset for HTTP 1.1 is ANSI because ANSI is identical to ISO-8859-1 . HTTP 1.1默认字符集是 ANSI,因为 ANSI 与ISO-8859-1相同。
Alse WebClient.Encoding by default is set to Encoding.Default that means you get ANSI code page.默认情况下, WebClient.Encoding设置为Encoding.Default ,这意味着您获得 ANSI 代码页。 All Default encodings lose data, so, you might use UTF-8 instead.所有默认编码都会丢失数据,因此,您可以改用 UTF-8。

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.因此,如果设置 charset 并不意味着所有内容都必须编码为 Unicode,而是意味着这些文档只能包含由 Unicode 定义的字符。 It means you also need to save your content as UTF-8.这意味着您还需要将内容保存为 UTF-8。 In that case you can use Encoding.UTF8.GetString()在这种情况下,您可以使用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.您可以使用WebClient.UploadValues(Uri, NameValueCollection)方法。 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.您甚至不需要指定Content-Type标头,因为它默认发送Content-Type: application/x-www-form-urlencoded

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这就是我如何实现我的 post 方法

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这发送了 123%456 并且数据没有转换为 123%456,我使用 ASP.net Web API,Json.Stringify 使用 .net Json 序列化

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当我尝试使用 GET 方法时,我也面临同样的问题,密码参数包含 % 字符,Api 继续对其进行解码,因此 123$45 解码为 123E6,因此我只需将 % 替换为 %25 就可以了

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

Here some links help me MSDN , ASCII Encoding Reference这里有一些链接帮助我MSDNASCII 编码参考

I recently had the same problem with a 3rd party API.我最近在使用 3rd 方 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.对我有用的是 UploadDataAsync。 In my case special characters (é, ü, ã etc) would cause an error when sending the json string to the API.在我的情况下,将 json 字符串发送到 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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试使用Content-Type application / x-www-form-urlencoded来访问API - Trying to reach API using Content-Type application/x-www-form-urlencoded C# HttpClient REST 请求使用 Content-Type: application/x-www-form-urlencoded - C# HttpClient REST request using Content-Type: application/x-www-form-urlencoded 使用内容类型application / x-www-form-urlencoded解析从HTTP POST接收的C#中的JSON数据 - Parsing JSON data in C# received from HTTP POST with content-type application/x-www-form-urlencoded JSON POST,其内容类型为x-www-form-urlencoded的数组参数 - JSON POST with an array parameter with content-type x-www-form-urlencoded 如何以Content-Type的形式返回响应:application / x-www-form-urlencoded; 从WCF服务? - How to return response as Content-Type: application/x-www-form-urlencoded; from WCF service? RestSharp在POST上将Content-Type默认为application / x-www-form-urlencoded - RestSharp defaulting Content-Type to application/x-www-form-urlencoded on POST 在WCF ReSTful服务中,POST或PUT请求的Content-Type是否需要为“ application / x-www-form-urlencoded”? - Does the Content-Type of a POST or PUT request need to be 'application/x-www-form-urlencoded' in a WCF ReSTful service? 使用 application/x-www-form-urlencoded 内容类型处理请求,但 NET Core 中的 XML 主体 Web API - Handle Request with application/x-www-form-urlencoded content-type but XML body in NET Core Web API 使用C#获取Webhooks以JSON形式获取内容类型为x-www-form-urlencode的请求消息 - Getting a request message with a content type x-www-form-urlencoded in a form of JSON using C# for webhooks 如何使用 HTTPclient content type = application/x-www-form-urlencoded POST - How to POST using HTTPclient content type = application/x-www-form-urlencoded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM