• PHP调用接口用post方法传送json数据


    1、核心代码:

    <?php
    require("helper.php");
    header('content-type:text/html;charset=utf-8');
    
    $key = 'C43D436036E643F5AFA654FED758BCF7';
    
    //参数数组
    $post_data = array (
        "parter" => '2308',
        "orderid" => '201711021121',
    );
    
    //签名
    ksort($post_data);//键按ASCII码升序排序
    $preSignString=getPreSignString($post_data);
    $sign = md5($preSignString.'&key='.$key);
    $sign=strtoupper($sign);//大写
    
    //签名参数添加到参数数组
    $post_data['sign']=$sign;
    
    //参数转成json
    $parameters =json_encode($post_data);
    
    //发送请求
    $url='http://localhost:64781/api/Query/QueryStatus';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    
    //处理返回数据
    $responseData=json_decode($response,true);//发序列化为数组
    
    print_r($responseData);
    post.php

    2、工具类代码:

    <?php
    
    /*
     * 获取待签名字符串
     * */
    function getPreSignString($array)
    {
        $prestr='';
    
        if(empty($array))
            return $prestr;
        else
        {
            foreach($array as $key=>$value){
                if(!empty(trim($value)) && strtolower($key)!='sign') {
                    $prestr.=$key.'='.$value.'&';
                }
            }
    
            if(!empty($prestr)){
                $length=strlen($prestr);
                $prestr=substr($prestr,0,$length-1);//去掉最后一个‘&’
            }
    
            return $prestr;
        }
    }
    helper.php

     3、调试:

    3.1 远程接口接收数据包:

    以c#为例(以流的形式接收):

    Stream requestData = HttpContext.Current.Request.InputStream;
     //获取参数
     byte[] b = new byte[requestData.Length];
     requestData.Read(b, 0, (int)requestData.Length);
     string postdata = Encoding.UTF8.GetString(b);
    View Code

    postdata 结果如下:

    {"orderid":"201711021121","parter":"2308","sign":"A75F1B4687105C84666F0812AB24232D"}

    3.2 远程接口返回数据包(这里把接收的json转为数组):

    Array ( [orderid] => 201711021121 [ekaorderid] => 17110213495685030814 [opstate] => 1 [parter] => 2308 [ovalue] => 100.1000 [code] => 0000 [msg] => 成功 )
  • 相关阅读:
    b站评论爬取
    推算身份证的生日位
    mac安装mysql
    H3C V7版本的系统默认权限
    H3C IRF2的三种配置情况
    一张图看懂高通QC1.0-QC4.0快充进化之路!QC2.0跟QC3.0充电区别
    云服务器 ECS Linux 软件源自动更新工具
    透明代理、匿名代理、混淆代理、高匿代理有什么区别?
    ping正常但是ssh到linux服务器很卡的解决方法
    Python GUI编程(Tkinter) windows界面开发
  • 原文地址:https://www.cnblogs.com/qk2014/p/7778366.html
Copyright © 2020-2023  润新知