【问题标题】:Send HTTP post request to ASP.Net Web API using PHP使用 PHP 向 ASP.Net Web API 发送 HTTP 发布请求
【发布时间】:2017-12-11 07:46:56
【问题描述】:
<html>
 <body><input type="button" id="send" value="Send"></body>
</html>

在我的 html 中会有一个按钮, 当它被点击时,我想连接到http://localhost:81/Help/Api/POST-Login 这是我的api。 然后我想向它发布数据。 现在很困惑,任何想法。提前致谢

<?php

$url = "http://localhost:81/Help/Api/POST-Login";    

$data = array(
 'message'      => 'hi,
  mobile'    => 12345678,

);
$options = array(
'http' => array(
'method'  => 'POST',
'content' => json_encode( $data ),
'header'=>  "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n"
)
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

【问题讨论】:

  • 使用 cURL 进行这种传输。

标签: php asp.net web-services http asp.net-web-api


【解决方案1】:

使用以下代码从 .NET API 获取响应:

$url = "http://localhost:81/Help/Api/POST-Login";    

$data = array(  'message'      => 'hi,   mobile'    => 12345678,

);

$options = array(
        CURLOPT_CUSTOMREQUEST => "POST", //set request type post or get
        CURLOPT_POST => false, //set to GET
        CURLOPT_COOKIEFILE => "cookie.txt", //set cookie file
        CURLOPT_COOKIEJAR => "cookie.txt", //set cookie jar
        CURLOPT_RETURNTRANSFER => true, // return web page
        CURLOPT_HEADER => false, // don't return headers
        CURLOPT_FOLLOWLOCATION => true, // follow redirects
        CURLOPT_ENCODING => "", // handle all encodings
        CURLOPT_AUTOREFERER => true, // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
        CURLOPT_TIMEOUT => 120, // timeout on response
        CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;

echo $header['content'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2013-02-06
    • 2020-01-28
    • 2019-04-09
    • 1970-01-01
    相关资源
    最近更新 更多