我尝试使用Async方法在PHP页面上发布JSON字符串,如下所示:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace test_http
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/ABC/products.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("products/1");
Console.WriteLine(response.ToString());
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync(client.BaseAddress, gizmo);
Console.WriteLine(response.ToString());
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location;
// HTTP PUT
gizmo.Price = 80; // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
Console.WriteLine(response.ToString());
// HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
Console.WriteLine(response.ToString());
}
}
}
}
}
我在控制台窗口的POST,PUT和DELETE操作上获得200状态OK。但是PHP页面没有显示任何内容。 PHP代码:
<?php
$json = json_encode($_POST);
var_dump(json_decode($json));
?>
我发现正在发布的数据的内容类型显示为&#39; text / html&#39;在控制台而不是&#39; application / json&#39;因此PHP无法识别POST。但我不知道我在这里做错了什么。 有人可以帮忙吗?
答案 0 :(得分:0)
第1,没有必要使用json_encode
,因为你已经发送了json。
其次,只有在发送key:value对时才会填充phps global $_POST
。如果您要发送json,则应使用输入流:
<?php
var_dump(json_decode(file_get_contents('php://input')));