法语口音的Charset问题(WebRequest)

时间:2011-07-06 16:44:50

标签: c# facebook-graph-api

当我发送此webrequest时,其字符串包含queryParam["message"] = sMessage;中的“é”等特殊字符串到图表API,它将在facebook用户墙'%u00e9'上发布。 我用utf8和ISO-8859-1测试......

这是我的代码:

NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["access_token"] = facebookUser.accessToken;
string url = "https://graph.facebook.com/" + facebookUser.id + "/feed?" + queryString;

NameValueCollection queryParam = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryParam["name"] = name;
queryParam["link"] = link;
queryParam["picture"] = picture;
queryParam["description"] = description;
queryParam["source"] = source;
queryParam["caption"] = caption;
queryParam["actions"] = action;
queryParam["message"] = sMessage;

var webRequest = WebRequest.Create(url);
webRequest.ContentType = "text/html; charset=ISO-8859-1";
webRequest.Method = "POST";
//webRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8");
webRequest.Headers.Add("Accept-Language", "en-us,en;");
webRequest.Headers.Add(System.Net.HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8");
byte[] bytes = Encoding.UTF8.GetBytes(queryParam.ToString());
webRequest.ContentLength = bytes.Length;
System.IO.Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();

try
{
    var webResponse = webRequest.GetResponse();
    StreamReader sr = null;
    try
    {
        sr = new StreamReader(webResponse.GetResponseStream());
    }
    finally
    {
        if (sr != null)
        {
            sr.Close();
        }
    }
}

你有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您将字符集设置为ISO-8859-1,然后您正在使用Encoding.UTF8.GetBytes()。您应该使用Encoding.GetEncoding("ISO-8859-1").GetBytes()或(可能更好)始终使用UTF-8!

我看到你将AcceptCharset设置为UTF-8然后进行了评论。但是你忘记了ContentType