2011-11-06 50 views
9

我想從我的C#控制檯應用程序調用google url shortner API,我嘗試實現請求是:調用C#谷歌網址Shortner API

POST https://www.googleapis.com/urlshortener/v1/url

Content-Type: 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不支持解析表單編碼輸入。 我不知道如何解決這個問題。

回答

14

您可以檢查下面的代碼(利用System.Net的)。 你應該注意到contenttype必須被規定,並且必須是「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); 
      } 

     } 

    } 
} 
+0

'const string MATCH_PATTERN = @「」「id」「:?」「(?。+)」「」; Console.WriteLine(Regex.Match(responseText,MATCH_PATTERN).Groups [「id」]。Value);'獲取縮短的URL。 –

+0

應用程序/ json對我來說是缺失的部分。正在使用文本/ JSON,就像一個白癡。 – Jon

2

如何改變

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

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

它給出了這樣的錯誤:參數2:無法從「字符串」轉換爲System.Net.Http.HttpContent」 – SKandeel

+0

比較遺憾的是,更新了答案 –

+0

錯誤:‘System.Net.Http.HttpContent’呢不包含'CreateEmpty'的定義 – SKandeel

1

以下是我的工作代碼。可能對你有幫助。

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