你好,我正在尝试翻译用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得到错误答案,有人能帮助我找到代码中的错误吗?
2条答案
按热度按时间sg3maiej1#
PHP curl是否有效?
这不是基线文档所要求的。
该文档要求提供以下过帐数据:
您的PHP curl请求发布数据:
文档要求
您的参数是一个数组,而不是JSON。
lxkprmvk2#
好的我找出这个问题的解决方案:
最大的问题是数据的编码。***curl***在PHP中默认以x-www-form-urlencoded格式发送数据