【问题标题】:C# HttpWebRequest POST => !! Unexpected error while processing request: invalid %-encodingC# HttpWebRequest POST => !!处理请求时出现意外错误:无效的 %-encoding
【发布时间】:2012-07-13 19:03:33
【问题描述】:

我遇到了一个问题,我尝试从 C# 应用程序与 Ruby API 进行通信。

我需要 POST 一些 JSON 数据,参数名称为“data”,但 API 返回:'!!处理请求时出现意外错误:无效的 %-encoding'。

我尝试将 Content-Type 设置为 'application/json' 和 'application/x-www-form-urlencoded; charset=utf-8'。

我的 POST 数据看起来像这样 'data=some_json_string'。

我认为我应该转义 json 字符串,所以如果这是我的问题,如何在不使用 3rd 方库的情况下使用 .NET 来做到这一点?

代码:

        byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(sdata);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
        request.ContentLength = data.Length;

        Stream reqStream = request.GetRequestStream();

        // Send the data.
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();

提前致谢!

【问题讨论】:

  • 请你发布完整的c#代码

标签: c# .net json serialization


【解决方案1】:

假设传入的字符串 sdata 已经是 JSON 格式,您可以这样做:

using (WebClient wc = new WebClient())
{
    string uri = "http://www.somewhere.com/somemethod";
    string parameters = "data=" + Uri.EscapeDataString(sdata);
    wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
    string result = wc.UploadString(uri, parameters);
}

根据消费服务,它可能需要将 Content-type 设置为 application/json?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多