简体   繁体   English

C#HTTPListener编码问题

[英]c# HTTPListener encoding issue

I have a Java application sending HTTP requests to a C# application. 我有一个Java应用程序,它向C#应用程序发送HTTP请求。 The C# app uses HTTPListener to listen for requests and respond. C#应用程序使用HTTPListener侦听请求并做出响应。 On the Java side I'm encoding the URL using UTF-8. 在Java方面,我正在使用UTF-8编码URL。

When I send a \\ character it gets encoded as %5C as expected but on the C# side it becomes a / character. 当我发送\\字符时,它按预期被编码为%5C,但是在C#端,它变成了/字符。 The encoding for the request object is Windows-1252 which I think may be causing the problem. 请求对象的编码是Windows-1252,我认为这可能是导致问题的原因。 How do I set the default encoding to UTF-8? 如何将默认编码设置为UTF-8?

Currently I'm doing this to convert the encoding: 目前,我正在这样做以转换编码:

        foreach (string key in request.QueryString.Keys)
        {
            if (key != null)
            {
                byte[] sourceBytes =request.ContentEncoding.GetBytes(request.QueryString[key]);
                string value = Encoding.UTF8.GetString(sourceBytes));
             }
        }

This handles the non ASCII characters I'm also sending but doesn't fix the slash problem. 这可以处理我也要发送的非ASCII字符,但不能解决斜杠问题。 Examining request.QueryString[key] in the debugger shows that the / is already there. 在调试器中检查request.QueryString [key]显示/已经存在。

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

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

short: you have to add charset=utf-8 to content type in the response header. 简短:您必须在响应标头中将charset=utf-8添加到内容类型。

header shoud look like this. 标头应如下所示。 Content-Type = "text/plain; 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);

Long: 长:

response header of my http listener 我的HTTP侦听器的响应标头

//where is utf-8 ???  i need to put it somewhere here...!!!
Content-Length: 31
Content-Type: text/plain;    
Server: Microsoft-HTTPAPI/2.0

i inspected a web page that is capable to display utf-8 chars like turkish üğşİ 我检查了一个网页,该网页能够显示utf-8字符,如土耳其语üğşİ

response header from that utf-8 website 该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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM