You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向服务器应用发送数据?旧应用转Web Service技术咨询

可行替代方案及实现思路

1. JSON API(RESTful风格)

这是Web服务最通用的轻量方案,无需复杂页面,客户可通过curl、脚本或API调试工具发送请求:

  • 客户发送的JSON格式数据:
    {
      "hotel": "London North",
      "stars": 3,
      "rooms": 57,
      "presences": 12000
    }
    
  • 服务器端处理:
    • PHP:通过file_get_contents('php://input')获取请求体,用json_decode()解析为数组/对象;处理完成后用json_encode()返回JSON格式结果。
    • Python(Flask):用request.get_json()解析请求数据,处理后返回jsonify()包装的响应。
  • 返回示例:
    {
      "average_room_occupation": "15%",
      "yearly_shower_gel_consumption": 20000
    }
    

2. 原生纯文本格式直接收发

直接使用你给出的原始格式进行收发,无需转换格式,适合极简Demo:

  • 客户直接发送字符串:hotel = "London North", stars = 3, rooms = 57, presences = 12000
  • 服务器端解析:
    • PHP:用正则表达式提取键值对,示例代码:
      $input = file_get_contents('php://input');
      preg_match_all('/(\w+)\s*=\s*("?[^",]+"?)/', $input, $matches);
      $data = array_combine($matches[1], array_map(function($val) {
        return trim($val, '"');
      }, $matches[2]));
      // 转换数值类型
      $data['stars'] = (int)$data['stars'];
      $data['rooms'] = (int)$data['rooms'];
      $data['presences'] = (int)$data['presences'];
      
    • Python:用正则或字符串分割处理,示例代码:
      import re
      input_str = request.data.decode('utf-8')
      matches = re.findall(r'(\w+)\s*=\s*("?[^",]+"?)\s*(?:,|$)', input_str)
      data = {key: val.strip('"') for key, val in matches}
      # 转换数值类型
      data['stars'] = int(data['stars'])
      data['rooms'] = int(data['rooms'])
      data['presences'] = int(data['presences'])
      
  • 返回直接输出纯文本:average room occupation = 15%, yearly shower gel consumption = 20000

3. 表单格式(x-www-form-urlencoded)

客户通过curl或脚本发送表单键值对,实现简单:

  • 客户发送示例(curl命令):
    curl -X POST -d "hotel=London%20North&stars=3&rooms=57&presences=12000" http://your-service-endpoint
    
  • 服务器端处理:
    • PHP:直接通过$_POST超全局变量获取数据,如$_POST['hotel']、(int)$_POST['stars']。
    • Python(Flask):通过request.form.get('hotel')、int(request.form.get('stars'))获取数据。
  • 返回可选择纯文本或JSON格式,灵活度高。

4. YAML格式收发

YAML具有良好的可读性,适合手动构造数据的场景:

  • 客户发送的YAML数据:
    hotel: "London North"
    stars: 3
    rooms: 57
    presences: 12000
    
  • 服务器端处理:
    • PHP:安装symfony/yaml组件,用Yaml::parse()解析请求体。
    • Python:安装PyYAML库,用yaml.safe_load(request.data)解析数据。
  • 返回也可使用YAML格式,兼顾可读性和机器解析性。

参考资源方向

  • PHP:官方文档中json_decode/json_encode函数说明、php://input用法、正则表达式语法示例;Symfony YAML组件的基础使用教程。
  • Python:Flask框架的请求与响应处理章节、PyYAML库的官方文档、正则表达式re模块的使用指南。

内容的提问来源于stack exchange,提问作者Mauro Ghiglia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 07:57:09