【发布时间】:2017-02-03 02:07:44
【问题描述】:
尝试使用 HTTPClient 发布到 api.lob.com。在调试期间,intellisense 在 HTTPRequestMessage 中显示了一个值,但是,任务 httpresponsemessage 值根本没有显示任何内容。
根据本文click here构建代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
namespace HTTPClientAPICall
{
class Program
{
static void Main(string[] args)
{
callAPI();
}
static void callAPI()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.lob.com");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "test_xxxxxxxxxxxxxxxxxxxxxxxxxx", ""))));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/v1/verify");
request.Content = new StringContent("{\"address_line1\":\"1600 Pennsylvania Ave NW\",\"address_city\":\"Washington\",\"address_state\":\"DC\",\"address_zip\":\"20500\"}", Encoding.UTF8, "application/json");
client.SendAsync(request).ContinueWith
((responseTask) =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
}
}
}
对比
我曾研究过使用 RESTSharp,但更喜欢直接使用 C# 而没有额外的引用。
【问题讨论】:
标签: c# rest asp.net-web-api