使用自定义JSON BODY制作HTTP帖子的最佳方法是什么 [英] What's the best way to make a HTTP post with custom JSON BODY

查看:120
本文介绍了使用自定义JSON BODY制作HTTP帖子的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力:(用自定义JSON Body发出HTTP帖子请求,我用代码尝试了Alamofire:

I'm struggling :( to make an HTTP post request with a custom JSON Body, I have tried Alamofire with the code :

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正文中没有列表

But this is not working, I should delete the list to make it work, Why I can't have a list in my JSON body

我的JSON正文如下:

my JSON body looks like :

{
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List":[
        {
        "IdQuestion" : 5,
        "IdProposition": 2,
        "Time" : 32
        },
        {
        "IdQuestion" : 4,
        "IdProposition": 3,
        "Time" : 9
        }
    ]
}

是否有任何图书馆或任何您建议使这个HTTP帖子请求有效的工作?

Is there any library or anything you recommend to make this HTTP post request work ?

推荐答案

工作正常

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:

Then I wrote a test php file to view the result got from app:

<?
$d = json_decode($_POST['val']);
echo $d->IdUser;
echo "\n".$d->List[0]->IdQuestion;
?>

我看到了

以前用于发出POST请求的函数如下:

Function I used to make POST-request is below:

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()

    }

这篇关于使用自定义JSON BODY制作HTTP帖子的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆