在C#中调用google Url Shortener API

时间:2011-11-06 20:09:23

标签: c# .net httpwebrequest google-api

我想从我的C#控制台应用程序中调用google url 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不支持解析表单编码输入。 我不知道如何解决这个问题。

4 个答案:

答案 0 :(得分: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);
            }

        }

    }
}

答案 1 :(得分:3)

Google有一个使用Urlshortener API的NuGet包。可以找到详细信息here

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

ProxySupportedHttpClientFactory

如果您位于防火墙后面,则可能需要使用代理。以下是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) }; } } 的实现,在上面的示例中已注释掉。这归功于this blog post

long L1;
if ((L%N1) ==  0)
{
 L1 = Convert.ToInt64(L1_temp - 1);
}else
{
 L1 = Convert.ToInt64(Math.Floor(L1_temp));
}

答案 2 :(得分:2)

如何改变

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

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

答案 3 :(得分:0)

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

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