我正在努力:(使用自定义JSON Body发出HTTP发布请求,我尝试了Alamofire代码:
let list = [[Time: 30, IdQuestion: 6510, idProposition: 10], [Time: 30, IdQuestion: 8284, idProposition: 10]]
let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil)
let jsons = NSString(data: data!, encoding: NSUTF8StringEncoding)
Alamofire.request(.POST, "http://myserver.com", parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = jsons!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
.response { request, response, data, error in
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
println(dataString)
}
但是这不起作用,我应该删除列表以使其工作,为什么我的JSON主体中没有列表
我的JSON正文如下:
{
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List":[
{
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
},
{
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
}
]
}
是否有任何图书馆或您推荐的任何内容可以使这个HTTP帖子请求有效?
答案 0 :(得分:1)
工作正常
let list = [["Time": 30, "IdQuestion": 6510, "idProposition": 10], ["Time": 30, "IdQuestion": 8284, "idProposition": 10]]
let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil)
let post = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
httpPost("http://my1test.ru/stack/test.php", postData: "val="+post) {res,code in
println(res)
}
然后我写了一个测试php文件来查看从app获得的结果:
<?
$d = json_decode($_POST['val']);
echo $d->IdUser;
echo "\n".$d->List[0]->IdQuestion;
?>
我看到了
我以前用于发出POST请求的函数如下:
func httpPost(url:String, postData: String, completion: (String, Int) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept")
request.addValue("gzip, deflate, sdch", forHTTPHeaderField: "Accept-Encoding")
request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String, statusCode)
}
})
task.resume()
}