I have a Java application sending HTTP requests to a C# application. The C# app uses HTTPListener to listen fo开发者_JAVA技巧r requests and respond. On the Java side I'm encoding the URL using UTF-8.
When I send a \ character it gets encoded as %5C as expected but on the C# side it becomes a / character. The encoding for the request object is Windows-1252 which I think may be causing the problem. How do I set the default encoding to 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. Examining request.QueryString[key] in the debugger shows that the / is already there.
short:
you have to add charset=utf-8
to content type in the response header.
header shoud look like this. 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);
Long:
response header of my http listener
//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 üğşİ
response header from that utf-8 website
content-type: text/html; charset=utf-8 //so we have put it here like this.
content-length: 20270
content-encoding: gzip
...
Encode each query string variable as UTF8:
byte[] utf8EncodedQueryBytes = Encoding.UTF8.GetBytes(key);
精彩评论