HttpWebResponse和编码(奇怪的字符)

本文关键字:字符 编码 HttpWebResponse | 更新日期: 2023-09-27 18:17:23

我的问题是,当我发送POST到表单,然后他们是错误的字符。

我发送扩展ASCII:

█████████

POST后我得到:

-"——ˆ——"——ˆ——ˆ——ˆ——ˆ——ˆ——ˆ

我代码:

req = (HttpWebRequest)HttpWebRequest.Create("http://forum.com/);
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
    req.Method = "POST";
    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    req.Headers.Add("Accept-Language: en-us,en;q=0.5");
    req.Headers.Add("Accept-Encoding: gzip,deflate");
    req.Headers.Add("Accept-Charset: ISO-8859-1;q=0.7,*;q=0.7");
    req.KeepAlive = true;
    req.Headers.Add("Keep-Alive: 300");
    req.Referer = "http://www.google.com/";
    req.ContentType = "application/x-www-form-urlencoded";
    req.CookieContainer = _cookieJar;
    req.ServicePoint.Expect100Continue = false;
    byte[] bytedata =
        Encoding.GetEncoding("iso-8859-1").GetBytes("subject=" + HttpUtility.UrlEncode(subject.Replace("_", " ")) +
                           "&description=" + HttpUtility.UrlEncode(description));
    Stream requestStream = req.GetRequestStream();
    requestStream.Write(bytedata, 0, bytedata.Length);
    requestStream.Close();
    try
    {
        response = (HttpWebResponse)req.GetResponse();
    }
    catch (Exception ex)
    {
        MessageBox.Show("oh noes...");
    }
                break;

现场编码为ISO-8859-1

HttpWebResponse和编码(奇怪的字符)

我做到了:

private string Encode(string text)
        {
            text = HTMLEncodeSpecialChars(text);
            return HttpUtility.UrlEncode(text);
        }
        public string HTMLEncodeSpecialChars(string text)
        {
            StringBuilder sb = new System.Text.StringBuilder();
            foreach (char c in text)
            {
                if (c > 127) // special chars
                    sb.Append(String.Format("&#{0};", (int)c));
                else
                    sb.Append(c);
            }
            return sb.ToString();
        }