iOS : http Post using swift

冷暖自知 提交于 2020-01-15 08:04:13

问题


I figured it out solution at the bottom

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

this is not setting the HTTPRequest.POST

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

POST : [QueryDict : {}]

What am I missing here? Any help is appreciated

Solution :

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


回答1:


use https://github.com/Alamofire/Alamofire

easy networking :)

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
     .response { (request, response, data, error) in
                 println(request)
                 println(response)
                 println(error)
               }

you can use all of the below.

public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}



回答2:


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)

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



来源:https://stackoverflow.com/questions/30596114/ios-http-post-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!