smo*_*med 10 .net c# google-api httpwebrequest
我想从我的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;
Run Code Online (Sandbox Code Playgroud)
主要方法是:
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();
}
Run Code Online (Sandbox Code Playgroud)
我得到错误代码400:此API不支持解析表单编码输入.我不知道如何解决这个问题.
csg*_*csg 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12321 次 |
| 最近记录: |