我用HttpWebRequest发送url时,当url包含中文的时候,服务器接收到的全是,乱码,我什么方法都用过了,比如用UTF8Encoding转换字符串,指定content-type,指定content-language,都不行,请高手告诉我怎么办。谢谢附代码如下:
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(new UTF8Encoding().GetString(new UTF8Encoding().GetBytes(url)));
wr.ContentType = "text/html; charset=utf-8";
hwr.Headers["Content-Language"] = "utf-8";
HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(new UTF8Encoding().GetString(new UTF8Encoding().GetBytes(url)));
wr.ContentType = "text/html; charset=utf-8";
hwr.Headers["Content-Language"] = "utf-8";
HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
假如两边都是DONET平台,不需要编码就可以
Request.aspx.csWebRequest req = HttpWebRequest.Create("http://localhost/WebTest/Server.aspx?China=汉字");
WebResponse res = req.GetResponse();Server.aspx
string s = Request.QueryString["china"];
Response.Write(s);经跟踪,可以得到汉字如果是JAVA获取其他平台,建议所有汉字都先经过UNICODE编码
服务端接收后解码
UNICODE编码string code_unicode(string s)
{
string s1 = "";
int tmp;
Encoding targetEncoding;
byte[] encodedChars;
// Get the encoding for the specified code page.
targetEncoding = Encoding.GetEncoding(1201); // Get the byte representation of the specified string.
encodedChars = targetEncoding.GetBytes(s);
for (int i = 0; i < encodedChars.Length; i++)
{
tmp = encodedChars[i];
s1 = s1 + tmp.ToString("X2"); }
return s1;
}
那边是
public String transferCode(String a,String t) {
String s = "";
try {
byte b[] = a.getBytes("ISO-8859-1"); s = new String(b,t);
}
catch (java.io.UnsupportedEncodingException e) {
System.out.println("java.io.UnsupportedEncodingException !!!");
e.printStackTrace();
}
return s;
}
转换时用mycontent=transferCode(mycontent,"GBK");
服务器端我不能改,所以只能改C#里的代码,请问该怎么弄?
对 URL 字符串进行编码,以便实现从 Web 服务器到客户端的可靠的 HTTP 传输。
HttpUtility.UrlEncode(string str)对字符串进行 URL 解码并返回已解码的字符串。
HttpUtility.UrlDecode(string);看这两个方法能不能满足你的要求
string sFilename = "你好";
string serverurl = "http://localhost/a.aspx";
string filename = HttpUtility.UrlEncode(sFilename ,System.Text.Encoding.Default);
string url = string.Format("{0}?name={1}",serverurl,
filename);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);仅对中文部分编解码,会转换成%XX这样的形式,这样应该就可以了。
我想解决问题的方式就是不让HttpWebRequest自动编码,但是req.Address.AbsoluteUri却是只读的!所以,我也没有办法!不知道楼主解决这个问题没有,解决了的话,请楼主还是告诉大家吧,共同提高哦!