如何通过 POST 方法将数组发送到服务器?
Posted
技术标签:
【中文标题】如何通过 POST 方法将数组发送到服务器?【英文标题】:How to send array by POST method to server? 【发布时间】:2017-07-14 08:55:54 【问题描述】:我正在尝试将数组作为参数发送到服务器,但服务器没有接收到。服务器必须接收我发送的两个数组。但是在服务器中它们没有出现??我不知道是我的错误还是服务器的错误? 我的数组名称是 testAns 和 testQuest,我必须将其发送到参数:answer 和 quest。 我的代码:
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(testAns)&quest=\(testQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
print("error=\(String(describing: error))")
return
do
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
catch
print(error)
task.resume()
【问题讨论】:
在提出基本问题之前参考更多信息。 @Ragul 我已经编辑了,如果你知道请帮忙,如果有什么不明白的,请告诉我 看看我的回答,如果您有任何进一步的帮助,请告诉我。 这很大程度上取决于您的服务器如何接收数组。请显示服务器端代码或服务器的 API 参考。否则你可能需要玩持久的猜谜游戏...... 【参考方案1】:我不知道如何在您的服务器端对该数组进行编码。 但暂时您可以尝试这种方式并检查您的数据库。
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer[0]=131&answer[1]=123&quest[0]=123&quest[1]=233"
【讨论】:
您需要序列化答案数组,然后附加到 postString。 它是服务器端的php数组。需要这样发送。【参考方案2】:您可以使用此时非常流行的Alamofire,它是AFNetworking的高级版 另外,我正在分享帮助您访问 API 的方法,您只需在此方法中传递字典对象,这将在两个块中为您提供响应,您可以根据需要使用它们。
1:不可达()
2:处理程序(responseDict)
//MARK: *********** HIT POST SERVICE IN JSON FORM***********
func hitPostServiceJsonForm(_ params:Dictionary<String,Any>,unReachable:(() -> Void),handler:@escaping ((Dictionary<String,Any>?) -> Void))
if networkReachable() == false
unReachable()
let BASE_URL = "http://mydoamain"
var request = URLRequest(url: URL(string: BASE_URL)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
print(BASE_URL)
Alamofire.request(request).responseJSON response in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any>
print("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict)
else
handler(nil)
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8)
print("Server Response: \(utf8Text)") // original server data as UTF8 string
break
case .failure(let error):
handler(nil)
print(error)
break
func networkReachable() -> Bool
return (NetworkReachabilityManager()?.isReachable)!
【讨论】:
【参考方案3】:将您的数组转换为 json 字符串,然后尝试将其发送到服务器
func post_array()
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
var tempAns : NSString = ""
do
let arrJson = try JSONSerialization.data(withJSONObject: testAns, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempAns = string! as NSString
catch let error as NSError
print(error)
var tempQuest : NSString = ""
do
let arrJson = try JSONSerialization.data(withJSONObject: testQuest, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempQuest = string! as NSString
catch let error as NSError
print(error)
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(tempAns)&quest=\(tempQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
print("error=\(String(describing: error))")
return
do
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
catch
print(error)
task.resume()
【讨论】:
var tempAns : NSString = "" do let arrJson = try JSONSerialization.data(withJSONObject: testAns, options: .prettyPrinted) let string = NSString(data: arrJson, encoding: String.Encoding.utf8 .rawValue) tempAns = 字符串! as NSString catch let error as NSError print(error)以上是关于如何通过 POST 方法将数组发送到服务器?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 iOS 中使用 NSDictionary 添加图像并使用 POST 方法将数组列表发送到服务器
图像未通过 IOS 中的 POST 方法发送到 PHP Web 服务
WCF POST 通过 JQuery。如何在 JSON 中发送数组?