通过 Postman 和 C# WebRequest 测试调用时,它可以工作,但我无法使用带有 PostAsync 或 PostJsonAsync 调用的 HttpClient 来做同样的事情。
错误:不支持的媒体类型,尽管需要并应用了 application/json。
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://pos.api.here.com/positioning/v1/locate?app_id={id}&app_code={code}", content);
return response;
状态码:415,ReasonPhrase:“不支持的媒体类型”,版本:1.1,内容:System.Net.Http.HttpConnection+HttpConnectionResponseContent,标头:{ 日期:2019 年 11 月 8 日星期五 13:38:37 GMT 服务器:nginx-clojure 内容-类型:应用程序/json 内容长度:114}
网络请求
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (!string.IsNullOrEmpty(data))
{
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
return response;
}
}