Xamarin__HttpClient__HttpResponseMessage-Content --- 获取 HTML 而不是 JSON

Xamarin__HttpClient__HttpResponseMessage-Content --- Getting HTML instead of JSON

HttpClient myClient = new HttpClient();
myClient.BaseAddress = new Uri(URL);

已在客户端指定基址 URL。

var encodedObject = JsonConvert.SerializeObject(Obj);
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await myClient.PostAsync("test.php/yourAPI",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
  var responseContent =  response.ToString();
  var responsebody = response.Content.ToString();
  Stream receiveStream = response.GetResponseStream();
  string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
}

可能是内容协商问题。在添加 json 媒体类型

之前尝试清除 Accept header
myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//...other code removed for brevity.

此代码将 Accept header 设置为 "application/json",它告诉服务器以 [​​=23=] 格式发送数据。

参考来源:Calling a Web API From a .NET Client in ASP.NET Web API 2

方法 PostAsync 的第一个参数是 API 的完整 URI。因此,应该如下所示:

    HttpResponseMessage response = await myClient.PostAsync("http://bla-bla-bla/test.php/test",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));

并且无需定义 BaseAddress。