[英]No response from web api
尝试使用HTTPClient发布到api.lob.com。 在调试过程中,Intellisense会在HTTPRequestMessage中显示一个值,但是,任务httpresponsemessage值根本不显示任何内容。
根据这篇文章构建了代码, 请点击这里
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#。
在原始代码中犯了一些错误。 此解决方案正在工作。 通过这篇文章来确定最终解决方案的起点: 单击此处
解决方案的关键是JSON.NET。
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.Web.Configuration;
using Newtonsoft.Json;
namespace JSONandHTTPClient
{
class Program
{
static void Main(string[] args)
{
callJSONandHTTPClientApp();
}
static void callJSONandHTTPClientApp()
{
using (var client = new HttpClient())
{
var parameters = new Dictionary<string, string>();
parameters["address_line1"] = "1600 Pennsylvania Ave NW";
parameters["address_city"] = "Washington";
parameters["address_state"] = "DC";
parameters["address_zip"] = "20050";
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_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx", ""))));
var justJSON = JsonConvert.SerializeObject(parameters).ToString();
var value = new StringContent(justJSON, Encoding.UTF8, "application/json");
var response = client.PostAsync("v1/verify", value).Result;
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(
response.Content.ReadAsStringAsync()
.Result);
Console.WriteLine(content.ToString());
}
Console.ReadLine();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.