2010-04-23 146 views
0

我有一个Java应用程序发送HTTP请求到C#应用程序。 C#应用程序使用HTTPListener来侦听请求并进行响应。在Java方面,我使用UTF-8对URL进行编码。c#HTTPListener编码问题

当我发送一个\字符时,按照预期编码为%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]显示/已经存在。

回答

0

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

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

短: 必须添加charset=utf-8到的内容类型中的响应首部。

header header看起来像这样。 的Content-Type = “text/plain的;字符集= 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 
...