zoukankan      html  css  js  c++  java
  • 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] => 成功 )
  • 相关阅读:
    Navicat连接mysql出现10061/10060错误的解决
    对话守则
    一次Django admin bug解决的思维过程
    Think different
    SVN版本库的迁移
    Windows Phone 8 锁屏背景与通知
    Windows Phone 7 应用升级 Windows phone 8 方案预览 选择合适的 Key Feature
    从 windows phone7 到 windows phone 8 更新 如何设配两个版本
    windows phone 8 语音 Speech for Windows Phone 8
    windows phone 8 中的应用间通信
  • 原文地址:https://www.cnblogs.com/qk2014/p/7778366.html
Copyright © 2011-2022 走看看