這是示例代碼在JSON中發佈。 您的請求返回500錯誤結果。
工作樣品:
let urlString = "https://httpbin.org/post"
var request = URLRequest(url: URL(string:urlString)!)
// set the method(HTTP-POST)
request.httpMethod = "POST"
// set the header(s)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// set the request-body(JSON)
let params: [String: Any] = [
"count": 1,
"user": [
"id": "10",
"name": "jack"
]
]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
}catch{
print(error.localizedDescription)
}
// use NSURLSessionDataTask
let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
if (error == nil) {
let result = String(data: data!, encoding: .utf8)!
print(result)
} else {
print(error!)
}
})
task.resume()
工作樣品(狗吠):
let consumer_key = "YWRAq7EKtUk1U3wENMNKEvGgL"
let consumer_secret = "2e08byjGV1k0XvPcwUwBoIxMDT7RozjdmEdk03RqCvUMqtE7nH"
let access_token = "3681130275-Onust8RaEz7Yczw07sWz52vLsEnxRCnnFDXZ5qA"
let access_token_secret = "dwLn951PF4bCh96xd170NCGpgOb5iRkqwgoNvTignDEMq"
let urlString = "https://api.yelp.com/v3/businesses/search"
var request = URLRequest(url: URL(string:urlString)!)
// set the method(HTTP-POST)
request.httpMethod = "POST"
// set the header(s)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(access_token, forHTTPHeaderField: "Authorization")
// set the request-body(JSON)
let params: [String: Any] = ["Authorization":access_token_secret]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
}catch{
print(error.localizedDescription)
}
// use NSURLSessionDataTask
let task = URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
if (error == nil) {
let result = String(data: data!, encoding: .utf8)!
print("result:\(result)")
// 500 Internal Server Error
} else {
print(error?.localizedDescription ?? "error")
}
})
task.resume()
嘗試這由Yelp的提供https://github.com/codepath/ios_yelp_swift/tree/master/Yelp – Vinodh
@Vinodh您提供的源代碼是使用Yelp V2。 OP正在使用Yelp V3。 – htjohn