首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebClient.UploadString方法不发出BOM。为什么?

WebClient.UploadString方法不发出BOM。为什么?
EN

Stack Overflow用户
提问于 2011-04-20 13:28:41
回答 1查看 1.2K关注 0票数 4

以下代码的目的是通过HTTP发布以字节顺序标记(BOM)开头的数据。

代码语言:javascript
复制
var client = new WebClient();
client.Encoding = new UTF8Encoding(true /* encoderShouldEmitUTF8Identifier */);
client.UploadString(url, data);

然而,根据小提琴,没有BOM在开始的请求主体。即使我使用UnicodeEncoding而不是UTF8Encoding,BOM也不会发送。

所以问题是,我做错了什么?

注意:我知道结合使用WebClient.UploadDataEncoding.GetPreamble方法可以绕过这个问题,但是我想知道为什么UploadString不能像我预期的那样工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-23 21:34:43

您没有做任何错误的事情,只是WebClient.UploadString没有调用Encoding.GetPreamble -它只是在您传递的字符串上调用Encoding.GetBytes。在HTTP请求中,如果要传递字符串,通常会在内容类型标头(charset参数)中指示编码,而不是在文件中内联(参见下面的示例)。UploadString就是这样做的(它是为“公共情况”量身定做的)。正如您提到的,如果您需要额外的东西,您可以直接上传字节。

代码语言:javascript
复制
public class StackOverflow_5731102
{
    [ServiceContract]
    public class Service
    {
        [WebInvoke]
        public Stream Process(Stream input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var header in WebOperationContext.Current.IncomingRequest.Headers.AllKeys)
            {
                sb.AppendLine(string.Format("{0}: {1}", header, WebOperationContext.Current.IncomingRequest.Headers[header]));
            }

            string contentType = WebOperationContext.Current.IncomingRequest.ContentType;
            Encoding encoding = Encoding.GetEncoding(contentType.Substring(contentType.IndexOf('=') + 1));
            WebOperationContext.Current.OutgoingResponse.ContentType = WebOperationContext.Current.IncomingRequest.ContentType;
            return new MemoryStream(encoding.GetBytes(sb.ToString()));
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        foreach (var encoding in new Encoding[] { new UTF8Encoding(true), new UnicodeEncoding(false, true) })
        {
            Console.WriteLine("Sending encoding = {0}", encoding.WebName);
            WebClient client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType] = "text/plain; charset=" + encoding.WebName;
            client.Encoding = encoding;
            string url = baseAddress + "/Process";
            string data = "hello";
            string result = client.UploadString(url, data);
            Console.WriteLine(result);

            Console.WriteLine(string.Join(",", encoding.GetBytes(data).Select(b => b.ToString("X2"))));
        }

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5731102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档