iOS:http Post使用swift [英] iOS : http Post using swift

查看:396
本文介绍了iOS:http Post使用swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在底部找到解决方案

I figured it out solution at the bottom

我正在尝试发布HTTP帖子请求到我的服务器。这就是我做的事情

I am trying to make an HTTP post request to my server. Here's what I did

        var request : NSMutableURLRequest = NSMutableURLRequest(URL : NSURL(string : "myURL")
        let session : NSURLSession = NSURLSession.sharedSession()
        request.allHTTPHeaderFields = (headers as [NSObject : AnyObject])
        request.HTTPShouldHandleCookies = true
        request.HTTPMethod = "POST"
        var postData = "frontend=iOS"
        request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
        println(request.allHTTPHeaderFields)
        println(request.HTTPBody)
        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data)
            println(json)
            onCompletion(json, error)
        })
       task.resume()

这不是设置HTTPRequest.POST

this is not setting the HTTPRequest.POST

我尝试将请求打印到服务器端的服务器上。 IT表示帖子是空的

I tried printing the request to the server on the server side. IT said post was empty


POST:[QueryDict:{}]

POST : [QueryDict : {}]

我在这里缺少什么?任何帮助表示赞赏

What am I missing here? Any help is appreciated

解决方案:


我错误地设置了内容值到application / json实际上它是
不是json的身体。删除它解决了问题

I mistakenly set the content-value to application/json when in fact it was not a json body. Removing it solved the problem


推荐答案

继承我在日志库中使用的方法: https://github.com/goktugyil/QorumLogs

Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs

    var url = NSURL(string: urlstring)

    var request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
    var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)

参见如何在正确编码的路上逃避Swift中的HTTP参数键值对数据字符串。

See How to escape the HTTP params in Swift on the way to correctly encode key-value pairs into the data string.

这篇关于iOS:http Post使用swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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