HttpWebResponse和编码(奇怪的字符)

时间:2011-12-11 00:16:45

标签: c# encoding httpwebresponse

我的问题是,当我将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。

1 个答案:

答案 0 :(得分:1)

I DID IT:

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();
        }