curl 将POST请求转换为PHP中API到Swift

vfh0ocws  于 2022-11-13  发布在  PHP
关注(0)|答案(2)|浏览(192)

你好,我正在尝试翻译用PHP编写的POST请求API代码:

<?php
$methodParams = '{
    "date_confirmed_from": 1407341754,
    "get_unconfirmed_orders": false
}';
$apiParams = [
    "method" => "getOrders",
    "parameters" => $methodParams
];

$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);

但我不知道为什么它不工作:

import UIKit

struct Parameters: Codable {
    let date_confirmed_from: Int
    let get_unconfirmed_orders: Bool
}

struct BodyData: Codable {
    let method: String
    let parameters:Parameters
}

let url = URL(string: "https://api.baselinker.com/connector.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = [
    "X-BLToken": "xxx"
]

let bodyData = BodyData(method: "getOrders", parameters: Parameters(date_confirmed_from: 1407341754, get_unconfirmed_orders: false))
let encoder = JSONEncoder()
do {
    let encodeData = try encoder.encode(bodyData)
    request.httpBody = encodeData
    let session = URLSession(configuration: .default)
    let task = session.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print(error)
        }
        if  let data = data {

        }
    }
    task.resume()
    
    
}catch {
    print(error)
}

当我测试我的Swift代码时,我从API得到错误答案,有人能帮助我找到代码中的错误吗?

sg3maiej

sg3maiej1#

PHP curl是否有效?
这不是基线文档所要求的。
该文档要求提供以下过帐数据:

array (
  'method' => 'getOrders',
  'parameters' => '{"date_from": 1407341754}',
)

您的PHP curl请求发布数据:

'array (
  'method' => 'getOrders',
  'parameters' => '{
    "date_confirmed_from": 1407341754,
    "get_unconfirmed_orders": false
}',
)'

文档要求

  • parameters = JSON格式的所请求函数的参数 *。

您的参数是一个数组,而不是JSON。

lxkprmvk

lxkprmvk2#

好的我找出这个问题的解决方案:

import UIKit

let url = URL(string: "https://api.baselinker.com/connector.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Accept")
request.setValue("xxx",forHTTPHeaderField: "X-BLToken")

let data: Data = "method=getOrders&parameters={\"date_confirmed_from\": 1407341754&\"get_unconfirmed_orders\":false}".data(using: .utf8)!
    request.httpBody = data
    let session = URLSession(configuration: .default)
    let task = session.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print(error)
        }
        if  let data = data {
            let dataString = String(data: data, encoding: .utf8)
            print(dataString!)
        }
    }
    task.resume()

最大的问题是数据的编码。***curl***在PHP中默认以x-www-form-urlencoded格式发送数据

相关问题