post json 在 swift 中请求
post json request in swift
我知道如何post简单json:
// Compose a query string
let postString = “firstName=James&lastName=Bond”;
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
现在服务器端需要 json 格式,例如:
{
"name": "testuser123",
"pass": "testuser123",
"field_shouji":
{ "und":
[{
"value": "15652344931"
}]
}
}
内容类型应为:application/json。我在谷歌上搜索了一整天,还是找到了正确的方法。
您需要发送 JSON 的有效格式。
“firstName=James&lastName=Bond”;
不是 JSON 格式。
Swift 4
由于 Swift 3 和 4 Apple 开始删除 NS*
东西(即使其中许多只是 NS*
的别名)我们将使用更多 Swift
方式
//Method just to execute request, assuming the response type is string (and not file)
func HTTPsendRequest(request: URLRequest,
callback: @escaping (Error?, String?) -> Void) {
let task = URLSession.shared.dataTask(with: request) { (data, res, err) in
if (err != nil) {
callback(err,nil)
} else {
callback(nil, String(data: data!, encoding: String.Encoding.utf8))
}
}
task.resume()
}
// post JSON
func HTTPPostJSON(url: String, data: Data,
callback: @escaping (Error?, String?) -> Void) {
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpBody = data
HTTPsendRequest(request: request, callback: callback)
}
用法示例
var dict = Dictionary<String, Any>()
dict["username"] = "hello"
dict["password"] = "swift"
let data = try JSONSerialization.data(withJSONObject: dict, options: [])
HTTPPostJSON(url: "http://example.com/login", data: data) { (err, result) in
if(err != nil){
print(err!.localizedDescription)
return
}
print(result ?? "")
}
Swift < 4
func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession()
.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,
encoding: NSUTF8StringEncoding)! as String, nil)
}
}
task.resume()
}
func HTTPPostJSON(url: String, data: NSData,
callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.HTTPBody = data
HTTPsendRequest(request, callback: callback)
}
用法示例
我们将设置 NSMutableDictionary
并将其转换为 JSON
var json = NSMutableDictionary()
json.setValue("testuser123", forKey: "name"); //set all your values..
let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(0), error: nil);
HTTPPostJSON("http;..", data:data!) { (response, error) -> Void in
println(response);
}
在上面的答案中,一行代码应更改如下
var json = NSDictionary()
代码应更改为
let json = NSMutableDictionary()
因为 NSDictionary() 是不可变的而 NSMutableDictionary() 是可变的
我知道如何post简单json:
// Compose a query string
let postString = “firstName=James&lastName=Bond”;
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
现在服务器端需要 json 格式,例如:
{
"name": "testuser123",
"pass": "testuser123",
"field_shouji":
{ "und":
[{
"value": "15652344931"
}]
}
}
内容类型应为:application/json。我在谷歌上搜索了一整天,还是找到了正确的方法。
您需要发送 JSON 的有效格式。“firstName=James&lastName=Bond”;
不是 JSON 格式。
Swift 4
由于 Swift 3 和 4 Apple 开始删除 NS*
东西(即使其中许多只是 NS*
的别名)我们将使用更多 Swift
方式
//Method just to execute request, assuming the response type is string (and not file)
func HTTPsendRequest(request: URLRequest,
callback: @escaping (Error?, String?) -> Void) {
let task = URLSession.shared.dataTask(with: request) { (data, res, err) in
if (err != nil) {
callback(err,nil)
} else {
callback(nil, String(data: data!, encoding: String.Encoding.utf8))
}
}
task.resume()
}
// post JSON
func HTTPPostJSON(url: String, data: Data,
callback: @escaping (Error?, String?) -> Void) {
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpBody = data
HTTPsendRequest(request: request, callback: callback)
}
用法示例
var dict = Dictionary<String, Any>()
dict["username"] = "hello"
dict["password"] = "swift"
let data = try JSONSerialization.data(withJSONObject: dict, options: [])
HTTPPostJSON(url: "http://example.com/login", data: data) { (err, result) in
if(err != nil){
print(err!.localizedDescription)
return
}
print(result ?? "")
}
Swift < 4
func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession()
.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,
encoding: NSUTF8StringEncoding)! as String, nil)
}
}
task.resume()
}
func HTTPPostJSON(url: String, data: NSData,
callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.HTTPBody = data
HTTPsendRequest(request, callback: callback)
}
用法示例
我们将设置 NSMutableDictionary
并将其转换为 JSON
var json = NSMutableDictionary()
json.setValue("testuser123", forKey: "name"); //set all your values..
let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(0), error: nil);
HTTPPostJSON("http;..", data:data!) { (response, error) -> Void in
println(response);
}
在上面的答案中,一行代码应更改如下
var json = NSDictionary()
代码应更改为
let json = NSMutableDictionary()
因为 NSDictionary() 是不可变的而 NSMutableDictionary() 是可变的