简体   繁体   中英

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

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

There'll be a button in my html, When it's clicked, i'd like to connect to http://localhost:81/Help/Api/POST-Login which is my api. Then i'd like to post data to it. Pretty confused now, any ideas guys. Thanks in advance

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

Use the below code to get the response from .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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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