[英]c# HTTPListener encoding issue
我有一个Java应用程序,它向C#应用程序发送HTTP请求。 C#应用程序使用HTTPListener侦听请求并做出响应。 在Java方面,我正在使用UTF-8编码URL。
当我发送\\字符时,它按预期被编码为%5C,但是在C#端,它变成了/字符。 请求对象的编码是Windows-1252,我认为这可能是导致问题的原因。 如何将默认编码设置为UTF-8?
目前,我正在这样做以转换编码:
foreach (string key in request.QueryString.Keys)
{
if (key != null)
{
byte[] sourceBytes =request.ContentEncoding.GetBytes(request.QueryString[key]);
string value = Encoding.UTF8.GetString(sourceBytes));
}
}
这可以处理我也要发送的非ASCII字符,但不能解决斜杠问题。 在调试器中检查request.QueryString [key]显示/已经存在。
将每个查询字符串变量编码为UTF8:
byte[] utf8EncodedQueryBytes = Encoding.UTF8.GetBytes(key);
简短:您必须在响应标头中将charset=utf-8
添加到内容类型。
标头应如下所示。 Content-Type =“文本/纯文本; charset = utf-8”
var text = "Hello World - Barkod Çözücü";
var buffer = Encoding.UTF8.GetBytes(text);
ctx.Response.ContentEncoding = Encoding.UTF8; // this doesnt work??
ctx.Response.ContentType = "text/plain; charset=utf-8"; //Fixxxx
ctx.Response.ContentLength64 = buffer.Length;
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
长:
我的HTTP侦听器的响应标头
//where is utf-8 ??? i need to put it somewhere here...!!!
Content-Length: 31
Content-Type: text/plain;
Server: Microsoft-HTTPAPI/2.0
我检查了一个网页,该网页能够显示utf-8字符,如土耳其语üğşİ
该utf-8网站的响应标头
content-type: text/html; charset=utf-8 //so we have put it here like this.
content-length: 20270
content-encoding: gzip
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.