0
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;
}
4

2 回答 2

0

方法 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。

于 2016-07-06T15:08:48.777 回答
0

可能是内容协商问题。在添加 json 媒体类型之前尝试清除Accept标题

myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//...other code removed for brevity.

此代码将 Accept 标头设置为“application/json”,它告诉服务器以 JSON 格式发送数据。

参考来源:在 ASP.NET Web API 2 中从 .NET 客户端调用 Web API

于 2016-07-05T12:30:40.523 回答