2011-11-06 6 views
9

voglio chiamare il google url shortner API dal mio C# applicazione console, la richiesta cerco di implementare è:chiamando API Google URL Shortner in C#

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

Content-Type: application/json

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

Quando provo ad usare questo codice:

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

e il metodo principale è:

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

ottengo il codice di errore 400: Questa API non supporta l'analisi input codificato in forma. Non so come risolvere questo problema.

risposta

14

è possibile controllare il codice qui sotto (fatto uso di System.Net). Si dovrebbe notare che il contenttype deve essere specfiato e deve essere "application/json"; e anche la stringa da inviare deve essere in formato 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); 'ottiene l'URL di riduzione. –

+0

application/json era il pezzo mancante per me. Stavo usando testo/JSON, come un idiota. – Jon

2

Come di cambiare

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

a

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

dà questo errore: Argomento 2: non è possibile convertire da 'stringa' per System.Net.Http.HttpContent' – SKandeel

+0

Mi dispiace, aggiornato la risposta –

+0

Errore: 'System.Net.Http.HttpContent' fa non contiene una definizione per "CreateEmpty" – SKandeel

1

Di seguito è riportato il mio codice di lavoro. Potrebbe essere utile per te.

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 ha un pacchetto NuGet per l'utilizzo dell'API Urlshortener. Dettagli possono essere trovati here.

Sulla base this example si implementa come tale:

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

Se sei dietro un firewall potrebbe essere necessario utilizzare un proxy. Di seguito è riportata un'implementazione dello ProxySupportedHttpClientFactory, che è commentato nell'esempio sopra. Il credito per questo va a 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) 
     }; 
    } 
}