HTTP-запрос с использованием метода по умолчанию GET вместо POST
Я пытаюсь отправить смс через 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)
}
}
Пожалуйста, посмотрите на скриншот, запрос опубликован как запрос "ПОЛУЧИТЬ". Пожалуйста, помогите мне решить эту проблему.
2 ответа
Решение
Я вроде понял, в чем была ошибка. Я должен был положить сообщение / в URL.
До: NSURL(строка:"https://"(authId)":"\ (authToken)"@api.plivo.com/v1/Account/"(authId)"/Message")
Правильный ответ: NSURL(строка: "https: //" (authId) ":" \ (authToken) "@ api.plivo.com/v1/Account/"(authId)"/Message /")
Без "/" в конце, запрос будет опубликован как "GET" вместо "POST". Надеюсь, это поможет другим.
Я вроде понял это, поэтому код выглядит так:
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()