使用PHP将HTTP post请求发送到ASP.Net Web API

时间:2017-07-07 06:00:42

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

<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 );

1 个答案:

答案 0 :(得分:0)

使用以下代码从.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'];