通过C#和UTF-8字符集使用HttpWebRequest

5

我正在尝试使用c#向我的电子商店发送一些带有希腊字符的数据。问题是,在电子商店中,希腊字符看起来像???????? ??????? 150?250

以下是我的c#代码。如果有人知道如何解决,请帮忙。

                EShopProduct eshopProduct = new EShopProduct();
                eshopProduct = GetEShopProductByProductCode(reference);

                string scode = eshopProduct.SCode;
                string name = eshopProduct.Name;
                string description = eshopProduct.Description;
                string quantity = eshopProduct.Quantity;
                string category = eshopCategoryId;
                string price = eshopProduct.Price;

                string postData = String.Format("scode={0}&name={1}&description={2}&quantity={3}&category={4}&price={5}&reference={6}",
                                                 scode, name, description, quantity, category, price, reference);

                string getUrl = _eshopUrl + "/insert_a_product_bysgs.php";

                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
                getRequest.Method = WebRequestMethods.Http.Post;
                getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; // SGS Galaxy
                getRequest.AllowWriteStreamBuffering = true;
                getRequest.ProtocolVersion = HttpVersion.Version11;
                getRequest.AllowAutoRedirect = true;
                getRequest.ContentType = "application/x-www-form-urlencoded";

                byte[] byteArray = Encoding.ASCII.GetBytes(postData);
                getRequest.ContentLength = byteArray.Length;
                Stream newStream = getRequest.GetRequestStream(); //open connection
                newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
                newStream.Close();

                HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
                using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) {
                    new_product_id = sr.ReadToEnd();
                }

1
你正在使用 ASCII 编码,而不是 UTF8。 - Moo-Juice
你说得对,谢谢。我明白了,我只是发布了问题并解决了它,然后你回答了。非常感谢!现在它可以正常工作了! - A. Zalonis
1个回答

10

您可以使用

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

该编码支持特殊字符,例如希腊字母,这些字符不包括在ASCII等价字符集中。

byte[] byteArray = Encoding.ASCII.GetBytes(postData);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接