Ascii编码正在放弃英镑

时间:2017-11-14 12:13:19

标签: c# encoding google-url-shortener

我正在使用Google Shortener,我能找到的唯一工作示例(如下)对URL字符串ASCII进行编码。问题是,当链接包含£时,ASCII将其替换为?。这意味着当链接缩短并单击时,URL不正确。我已经尝试了很多不同的编码,但这会阻止谷歌缩短工作。我要么想出一个谷歌将允许或更改代码的缩短编码。我宁愿做前者。有什么帮助吗?

public static string ShortenItBasic(string url, ref string returnedJson, ref bool succeeded, string urlShortenerId = null)
    {
        string finalURL = null;
        string post = "{\"longUrl\": \"" + url + "\"}";
        string urlShortener = null;

        if (!string.IsNullOrEmpty(urlShortenerId))
        {
            urlShortener = urlShortenerId;
        }
        else
        {
            urlShortener = ConfigKeys.GoogleShortenerAPIKey;
        }

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + urlShortener);
        try
        {
            request.ServicePoint.Expect100Continue = false;
            request.Method = "POST";
            request.ContentLength = post.Length;
            request.ContentType = "application/json";
            request.Headers.Add("Cache-Control", "no-cache");

            using (Stream requestStream = request.GetRequestStream())
            {
                byte[] postBuffer = null;

                if (ConfigKeys.IsDebugMode)
                {
                    postBuffer = Encoding.GetEncoding("IBM437").GetBytes(post);

                    //postBuffer = Encoding.ASCII.GetBytes(post);
                }
                else
                {
                    postBuffer = Encoding.ASCII.GetBytes(post);
                }

                requestStream.Write(postBuffer, 0, postBuffer.Length);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader responseReader = new StreamReader(responseStream))
                    {
                        string json = responseReader.ReadToEnd(); 

                        returnedJson = json;

                        finalURL = Regex.Match(json, @"""id"": ?""(?<id>.+)""").Groups["id"].Value;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // if Google's URL Shortener is down...
            Logging.LoggingIO.LogHelper("GoogleBitly: Issue with the shortener: <br/><br/>" + ex.Message + " Stack: " + ex.StackTrace);

            succeeded = false;

            return "There is a problem with the Google shortening service: " + ex.Message + ".  Please try another target";
        }

        succeeded = true;
        return finalURL;
    }

1 个答案:

答案 0 :(得分:0)

URL不能包含£字符,因为它不是ASCII字符。在URL中有效的一小部分ASCII之外的任何字符都必须是percent encoded,例如对于UTF-8编码的£为%C2%A3,对于ISO-8859-1编码的£为%A3(无论您的服务器更喜欢接收哪个)。构建URL时, URL-encode 您的值。