【问题标题】:PHP post to WebAPIPHP 发布到 WebAPI
【发布时间】:2015-04-25 19:24:18
【问题描述】:

好吧,我知道标题看起来很简单,但我从 3 天开始就在寻找有关如何将 POST 请求发送到 webapi 的示例。

目前我正在使用JQuery 来执行我的POST,但我需要一些php 脚本来运行并与我的C# webAPI 交谈,而且似乎不可能找到一些示例或解释如何做到这一点。

有人给了我然后代码:

$response = file_get_contents('http://localhost:59040/api/Email/SendEmails');
$response = json_decode($response);
echo ($response);

但是这个没有做任何事情 - 甚至没有关于如何深入解决问题的错误。

我只是需要一个 php 脚本来向 webapi 发出 POST 请求,该请求获得 1 个参数(字符串)并返回一个 ok 答案或错误,

【问题讨论】:

  • 这行得通,非常感谢。我如何为您的评论投票或回答?
  • 我很高兴它成功了。当您悬停评论时,您会在左侧看到一个向上的箭头。当评论有用时,您可以点击它。
  • 看来,如果你只有 1 星,你就做不到,对不起。
  • 语法和英语更正

标签: php post web asp.net-web-api


【解决方案1】:

在 Maalls 从这篇帖子中回答 How do I send a POST request with PHP?

答案很简单,代码如下:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

感谢 Maalls 和 dbau 的回答 :)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2013-05-13
    • 2018-09-10
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2013-11-06
    • 2014-03-19
    相关资源
    最近更新 更多