【问题标题】:calling google Url Shortner API in C#在 C# 中调用 google Url Shortener API
【发布时间】:2011-11-06 20:09:22
【问题描述】:

我想从我的 C# 控制台应用程序中调用 google url shortner API,我尝试实现的请求是:

发布https://www.googleapis.com/urlshortener/v1/url

内容类型:application/json

{"longUrl": "http://www.google.com/"}

当我尝试使用此代码时:

using System.Net;
using System.Net.Http;
using System.IO;

主要方法是:

static void Main(string[] args)
{
    string s = "http://www.google.com/";
    var client = new HttpClient();

    // Create the HttpContent for the form to be posted.
    var requestContent = new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("longUrl", s),});

    // Get the response.            
    HttpResponseMessage response = client.Post("https://www.googleapis.com/urlshortener/v1/url",requestContent);

    // Get the response content.
    HttpContent responseContent = response.Content;

    // Get the stream of the content.
    using (var reader = new StreamReader(responseContent.ContentReadStream))
    {
        // Write the output.
        s = reader.ReadToEnd();
        Console.WriteLine(s);
    }
    Console.Read();
}

我收到错误代码 400:此 API 不支持解析表单编码输入。 我不知道如何解决这个问题。

【问题讨论】:

    标签: c# .net httpwebrequest google-api


    【解决方案1】:

    您可以检查下面的代码(使用 System.Net)。 您应该注意到必须指定内容类型,并且必须是“application/json”;并且要发送的字符串必须是json格式。

    using System;
    using System.Net;
    
    using System.IO;
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
    
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"longUrl\":\"http://www.google.com/\"}";
                    Console.WriteLine(json);
                    streamWriter.Write(json);
                }
    
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    Console.WriteLine(responseText);
                }
    
            }
    
        }
    }
    

    【讨论】:

    • const string MATCH_PATTERN = @"""id"": ?""(?&lt;id&gt;.+)"""; Console.WriteLine(Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value); 获取缩短网址。
    • application/json 对我来说是缺失的部分。像个白痴一样使用 text/json。
    【解决方案2】:

    Google 有一个用于使用 Urlshortener API 的 NuGet 包。详情可见here

    基于this example,您可以这样实现它:

    using System;
    using System.Net;
    using System.Net.Http;
    using Google.Apis.Services;
    using Google.Apis.Urlshortener.v1;
    using Google.Apis.Urlshortener.v1.Data;
    using Google.Apis.Http;
    
    namespace ConsoleTestBed
    {
        class Program
        {
            private const string ApiKey = "YourAPIKey";
    
            static void Main(string[] args)
            {
                var initializer = new BaseClientService.Initializer
                {
                    ApiKey = ApiKey,
                    //HttpClientFactory = new ProxySupportedHttpClientFactory()
                };
                var service = new UrlshortenerService(initializer);
                var longUrl = "http://wwww.google.com/";
                var response = service.Url.Insert(new Url { LongUrl = longUrl }).Execute();
    
                Console.WriteLine($"Short URL: {response.Id}");
                Console.ReadKey();
            }
        }
    }
    

    如果您位于防火墙后面,则可能需要使用代理。下面是ProxySupportedHttpClientFactory 的实现,在上面的示例中被注释掉了。这归功于this blog post

    class ProxySupportedHttpClientFactory : HttpClientFactory
    {
        private static readonly Uri ProxyAddress 
            = new UriBuilder("http", "YourProxyIP", 80).Uri;
        private static readonly NetworkCredential ProxyCredentials 
            = new NetworkCredential("user", "password", "domain");
    
        protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
        {
            return new WebRequestHandler
            {
                UseProxy = true,
                UseCookies = false,
                Proxy = new WebProxy(ProxyAddress, false, null, ProxyCredentials)
            };
        }
    }
    

    【讨论】:

      【解决方案3】:

      换个方式

         var requestContent = new FormUrlEncodedContent(new[] 
              {new KeyValuePair<string, string>("longUrl", s),});
      

         var requestContent = new StringContent("{\"longUrl\": \" + s + \"}");
      

      【讨论】:

      • 它给出了这个错误:Argument 2: cannot convert from 'string' to System.Net.Http.HttpContent'
      • 错误:“System.Net.Http.HttpContent”不包含“CreateEmpty”的定义
      • 对不起,重新阅读完整的问题,发现我回答错了。请查看最新版本。
      【解决方案4】:

      以下是我的工作代码。可能对你有帮助。

      private const string key = "xxxxxInsertGoogleAPIKeyHerexxxxxxxxxx";
      public string urlShorter(string url)
      {
                  string finalURL = "";
                  string post = "{\"longUrl\": \"" + url + "\"}";
                  string shortUrl = url;
                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
                  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 = 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();
                                  finalURL = Regex.Match(json, @"""id"": ?""(?.+)""").Groups["id"].Value;
                              }
                          }
                      }
                  }
                  catch (Exception ex)
                  {
                      // if Google's URL Shortener is down...
                      System.Diagnostics.Debug.WriteLine(ex.Message);
                      System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                  }
                  return finalURL;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-09
        • 1970-01-01
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多