我正在学习C#和Web请求,因此我想从一个简单的帖子开始,然后将响应打印到控制台。
我已经用chrome和fiddler仔细检查了请求,在那里得到了正确的响应,但是在此程序中它返回“访问被拒绝”。
static async Task<string> GetWeatherAsync()
{
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("User-Agent", "WeatherAhead")
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.weather.gov/points/39.7456,-97.0892", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
URL是他们在weather.gov文档中提供的测试之一,并返回通过浏览器访问时所期望的json。
感谢您提供的任何帮助或建议!
答案 0 :(得分:0)
为客户端添加这些设置
client.BaseAddress = new Uri("http://api.weather.gov");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "web api client");
将您的功能更改为此并起作用
static async Task < string > GetWeatherAsync() {
client.BaseAddress = new Uri("http://api.weather.gov");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "web api client");
//var response = await client.GetAsync("https://api.weather.gov/points/39.7456,-97.0892");
var response = await client.GetAsync("/points/39.7456,-97.0892");
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}