繁体   English   中英

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

[英]Send HTTP post request to ASP.Net Web API using PHP

<html>
 <body><input type="button" id="send" value="Send"></body>
</html>

我的html中将有一个按钮,当单击它时,我想连接到作为我的api的http:// localhost:81 / Help / Api / POST-Login 然后,我想向其发布数据。 现在,有些想法的人很困惑。 提前致谢

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM