The WebClient.UploadString method does not generate a specification. What for?

The purpose of the following code is to send data starting with a byte byte (BOM) via HTTP.

var client = new WebClient(); client.Encoding = new UTF8Encoding(true /* encoderShouldEmitUTF8Identifier */); client.UploadString(url, data); 

However, according to the violinist, there is no specification at the beginning of the request body. The specification is not sent even if I use UnicodeEncoding instead of UTF8Encoding .

So the question is what am I doing wrong?

Note. I know that I can get around this problem using WebClient.UploadData in combination with the Encoding.GetPreamble method, however, I am wondering why UploadString does not work as I expected.

+4
source share
1 answer

You are not doing anything wrong, it's just that WebClient.UploadString does not call Encoding.GetPreamble - it just calls Encoding.GetBytes in the line you passed. For HTTP requests, if you pass strings, you usually specify the encoding in the content header (charset parameter) instead of the one embedded in the file (see the Example below). UploadString does this (it is for the "general case"). As you mentioned, if you want something extra, you can directly load the bytes.

 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
source

All Articles