0

我正在尝试通过 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”请求。请帮我解决这个问题。在此处输入图像描述

4

2 回答 2

1

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

之前:NSURL(string:"https://"(authId)":"\ (authToken)"@api.plivo.com/v1/Account/"(authId)"/Message")

正确一:NSURL(string:"https://"(authId)":"\(authToken)"@api.plivo.com /v1/Account/"(authId)" /Message/ ")

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

于 2016-05-13T15:41:53.430 回答
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()
于 2016-07-16T18:56:31.617 回答