在编码方面,以下哪种方法更好?
我写过三种方法,
Http POST请求
选项A - ASCII
let request = WebRequest.Create(url) :?> HttpWebRequest
request.Method <- "POST"
request.ContentType <- "application/json;charset=UTF-8"
use memoryStream = new MemoryStream()
(new DataContractJsonSerializer(typeof<Article>)).WriteObject(memoryStream, schema)
// option A
let str = Encoding.Default.GetString(memoryStream.ToArray()) // using ASCII
let data : byte[] = Text.Encoding.ASCII.GetBytes(str);
request.ContentLength <- (int64)data.Length
use requestStream = request.GetRequestStream()
requestStream.Write(data, 0, data.Length)
requestStream.Flush()
requestStream.Close()
选项B - UTF-8
let request = WebRequest.Create(url) :?> HttpWebRequest
request.Method <- "POST"
request.ContentType <- "application/json;charset=UTF-8"
use memoryStream = new MemoryStream()
(new DataContractJsonSerializer(typeof<Article>)).WriteObject(memoryStream, schema)
// option B
let s = Encoding.UTF8.GetString(memoryStream.ToArray()) // using UTF-8
let data : byte[] = Encoding.UTF8.GetBytes(d);
request.ContentLength <- (int64)data.Length
use requestStream = request.GetRequestStream()
requestStream.Write(data, 0, data.Length)
requestStream.Flush()
requestStream.Close()
选项C-直接内存流
let request = WebRequest.Create(url) :?> HttpWebRequest
request.Method <- "POST"
request.ContentType <- "application/json;charset=UTF-8"
use memoryStream = new MemoryStream()
(new DataContractJsonSerializer(typeof<Article>)).WriteObject(memoryStream, schema)
// option C direct memory stream to array
let data : byte[] = memoryStream.ToArray()
request.ContentLength <- (int64)data.Length
use requestStream = request.GetRequestStream()
requestStream.Write(data, 0, data.Length)
requestStream.Flush()
requestStream.Close()