c# - WebClient.UploadValues 的 UTF32?

标签 c#

我正在使用网络客户端在此处的后请求中上传值:

using (var client = new WebClient())
{

    client.Encoding = Encoding.UTF32;

    var parameters = new NameValueCollection
                         {
                             {"facebookID", IngamableCommunicator.FacebookProfileID + ""},
                             {"name", name},
                             {"content", File.ReadAllText(mapPath)}
                         };

    client.UploadValues(url, parameters);
}

如你所见,我认为这是将请求内容编码更改为UTF32的方法。我对吗?因为显然,它没有按预期工作。

最佳答案

您不能使用非 Ascii 编码的 UploadValues 方法,构建请求的内部方法:

// System.Net.WebClient
private byte[] UploadValuesInternal(NameValueCollection data)
{
    if (this.m_headers == null)
    {
        this.m_headers = new WebHeaderCollection(WebHeaderCollectionType.WebRequest);
    }
    string text = this.m_headers["Content-Type"];
    if (text != null && string.Compare(text, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != 0)
    {
        throw new WebException(SR.GetString("net_webclient_ContentType"));
    }
    this.m_headers["Content-Type"] = "application/x-www-form-urlencoded";
    string value = string.Empty;
    StringBuilder stringBuilder = new StringBuilder();
    string[] allKeys = data.AllKeys;
    for (int i = 0; i < allKeys.Length; i++)
    {
        string text2 = allKeys[i];
        stringBuilder.Append(value);
        stringBuilder.Append(WebClient.UrlEncode(text2));
        stringBuilder.Append("=");
        stringBuilder.Append(WebClient.UrlEncode(data[text2]));
        value = "&";
    }
    byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString());
    this.m_ContentLength = (long)bytes.Length;
    return bytes;
}

因此,它使用不设置编码的 Encoding.ASCII 或 WebClient.UrlEncode

使用 HttpWebRequest。

关于c# - WebClient.UploadValues 的 UTF32?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8561178/

相关文章:

java - C# 通过jdbc连接到sql

c# - 处理包装 IDispatch COM 接口(interface)的 c# 接口(interface)

c# - c#写mysql建表查询的方法

c# - SQL Server 2008 R2 Express Service Broker 正在使用所有空闲内存

c# - 在 C# 中容纳嵌套的不安全结构

c# - SelectedValue 无效 - 列表中不存在 - C#/ASP.NET

c# - 定义集合元素的 LINQ 语句问题

c# - Mono.Cecil 指令标签解析

c# - 使用 Autofac 的 ASP.NET Core v2.0 的 SignalR 依赖注入(inject)

c# - 无法使用 ASP.NET session 状态提供程序连接到 Redis 服务器