在C#中调用Google Url Shortner API [英] calling google Url Shortner API in C#

查看:140
本文介绍了在C#中调用Google Url Shortner API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的电话中调用 Google网址缩短API C#控制台应用程序,我试图实现的请求是:

I want to call the google url shortner API from my C# Console Application, the request I try to implement is:


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

内容类型:application / json

Content-Type: application/json

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

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

当我尝试使用此代码时:

When I try to use this code:

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

主要方法是:

and the main method is:

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不支持解析表单编码输入。
我不知道如何解决这个问题。

I get the error code 400: This API does not support parsing form-encoded input. I don't know how to fix this.

推荐答案

你可以检查下面的代码(使用System 。净)。
您应该注意到contenttype必须被规定,并且必须是application / json;并且要发送的字符串必须是json格式。

you can check the code below (made use of System.Net). You should notice that the contenttype must be specfied, and must be "application/json"; and also the string to be send must be in json format.

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

        }

    }
}

这篇关于在C#中调用Google Url Shortner API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆