2011-11-06 18 views
9

Quiero llamar la google url shortner API de mi C# aplicación de consola, la solicitud de trato de poner en práctica es:llamar a la API de Google Url Shortner en C#

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

Content-Type: application/json

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

Cuando trato de utilizar este código:

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

y el método principal es:

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

puedo obtener el código de error 400: Esta API no es compatible con el análisis sintáctico entrada codificada en forma. No sé cómo solucionar esto.

Respuesta

14

puede comprobar el código de abajo (hecho uso de System.Net). Debe observar que el tipo de contenido debe estar especificado, y debe ser "application/json"; y también la cadena que se enviará debe estar en 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 cadena MATCH_PATTERN = @" "" id "":? "" (? . +) "" "; Console.WriteLine (Regex.Match (responseText, MATCH_PATTERN) .Groups ["id"]. Value); 'obtiene la URL acortada. –

+0

application/json era la pieza que faltaba para mí. Estaba usando text/json, como un idiota. – Jon

2

¿Qué hay de cambiar

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

a

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

se da este error: Argumento 2: no se puede convertir de 'cadena' a System.Net.Http.HttpContent' – SKandeel

+0

Lo siento, actualizado el error –

+0

respuesta: 'System.Net.Http.HttpContent' hace no contiene una definición para 'CreateEmpty' – SKandeel

1

El siguiente es mi código de trabajo. Puede ser útil para usted.

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 tiene un paquete NuGet para utilizar la API de Urlshortener. Los detalles se pueden encontrar here.

Basado en this example implementarías como tal:

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

Si se encuentra detrás de un cortafuegos puede que tenga que utilizar un proxy. A continuación se muestra una implementación del ProxySupportedHttpClientFactory, que está comentada en el ejemplo anterior. El crédito para esto va al 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) 
     }; 
    } 
} 
Cuestiones relacionadas