request乱码指的是:浏览器向服务器发送的请求参数中包含中文字符,服务器获取到的请求参数的值是乱码;
response乱码指的是:服务器向浏览器发送的数据包含中文字符,浏览器中显示的是乱码;
乱码产生的原因:
不管是request乱码还是response乱码,其实都是由于客户端(浏览器)跟服务器端采用的编码格式不一致造成的。
以request乱码为例:
浏览器向服务器发送请求,因为浏览器与服务器之间的通信实质上是socket流,所以要先将请求参数(字符)转换成字节,也就是编码过程,服务器接收到请求参数后进行解码(字节转字符),然后封装到request对象中。如果客户端的编码与服务器端的解码不统一,就会导致通过request获取到的请求参数的值是乱码。
//GET请求
public static String HttpGetUrl(String url)
{
string strReturn = string.Empty;
String urlEsc = url;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(urlEsc);
req.Method = "GET";
try
{
using (WebResponse wr = req.GetResponse())
{
Stream stream = wr.GetResponseStream();
byte[] buf = new byte[1024];
while (true)
{
int len = stream.Read(buf, 0, buf.Length);
if (len <= 0)//len <= 0 跳出循环
break;
strReturn += System.Text.Encoding.GetEncoding("utf-8").GetString(buf, 0, len);//指定编码格式
}
}
}
catch (Exception ex)
{
throw ex;
}
return strReturn;
}
//POST请求
public static String HttpPostData(String url, String data)
{
string strReturn = string.Empty;
byte[] byteData = Encoding.UTF8.GetBytes(data); //在转换字节时指定编码格式
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = byteData.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(byteData, 0, byteData.Length);//发送数据
}
//get reponse data and parse
using (WebResponse response = httpWebReq.GetResponse())
{
using (WebResponse response = httpWebReq.GetResponse())
{
//解决乱码:utf-8 + streamreader.readtoend
StreamReader reader = new StreamReader(response.GetResponseStream() , Encoding.GetEncoding("utf-8"));
strReturn = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
StreamReader reader = new StreamReader(response.GetResponseStream() , Encoding.GetEncoding("utf-8"));
strReturn = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
return strReturn;
}