c#HTTPListener编码问题

时间:2010-04-23 06:01:16

标签: c# encoding httplistener

我有一个Java应用程序向C#应用程序发送HTTP请求。 C#app使用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]表明/已经存在。

2 个答案:

答案 0 :(得分:0)

将每个查询字符串变量编码为UTF8:

byte[] utf8EncodedQueryBytes = Encoding.UTF8.GetBytes(key);

答案 1 :(得分:0)

<强>短: 您必须在响应标头中添加charset=utf-8到内容类型。

标题看起来像这样。 Content-Type =“text / plain; 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字符的网页,如turkishüğşİ

来自该utf-8网站的回复标题

content-type: text/html; charset=utf-8    //so we have put it here like this.
content-length: 20270
content-encoding: gzip
...