HTTP请求采用默认方法GET而不是POST

时间:2016-05-12 23:45:31

标签: ios swift http https plivo

我试图通过Plivo SMS API发送短信。不幸的是,即使请求HTTP方法是' POST',请求也会发布为' GET'。请参阅下面的代码。

    let fromNumber = "11111111111"
    let toNumber = "111111234"
    let message = "Hello"

    do {
    let json = ["src":"\(fromNumber)","dst":"\(toNumber)","text":"\(message)"]
    let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
        print(jsonData)

    // Build the request
    let request = NSMutableURLRequest(URL: NSURL(string:"https://"\(authId)":"\(authToken)"@api.plivo.com/v1/Account/"\(authId)"/Message")!)

  // I'm assigning the method should be 'POST' but why its going as 'GET'

    request.HTTPMethod = "POST"  
    request.HTTPBody = jsonData

    // Build the completion block and send the request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()
        //return task



    } catch {
        print(error)
    }
}

请查看截图,请求发布为' GET'请求。请帮我解决这个问题。enter image description here

2 个答案:

答案 0 :(得分:1)

我有点弄清楚错误是什么。我应该把Message /放在网址中。

之前:NSURL(字符串:“https://”(authId)“:”\(authToken)“@ api.plivo.com/v1/Account /”(authId)“/消息”)

正确一个:NSURL(字符串:“https://”(authId)“:”\(authToken)“@ api.plivo.com/v1/Account /”(authId)“/ 消息/ < /强>“)

最后没有“/”,请求发布为“GET”而不是“POST” 希望它能帮助别人。

答案 1 :(得分:0)

我有点想通了,所以代码看起来像这样:

        let json = ["src":"Source","dst":"Destination","text":"Test SMS"]
        let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: [])
        print(jsonData)

        // Build the request
        let request = NSMutableURLRequest(URL: NSURL(string:"https://authID:authToken@api.plivo.com/v1/Account/authID/Message/")!)

        request.HTTPMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = jsonData

        // Build the completion block and send the request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: [])

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()