forked from Tencent/APIJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
114 lines (77 loc) · 3.22 KB
/
ViewController.swift
File metadata and controls
114 lines (77 loc) · 3.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//
// ViewController.swift
// testswift
//
// Created by Tommy on 17/11/28.
// Copyright © 2017年 APIJSON. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
test()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
* 通过POST请求测试APIJSON
*/
func test() {
//生成UI <<<<<<<<<<<<<<<<<<<<<<
let requestLabel = UILabel(frame:CGRect(x:20, y:10, width:400, height:130))
requestLabel.text = "Request:\n{\n \"User\": {\n \"sex\": 1\n }\n}"
requestLabel.numberOfLines = 6
self.view.addSubview(requestLabel)
let responseLable = UILabel(frame:CGRect(x:20, y:130, width:400, height:600))
responseLable.text = "request..."
responseLable.numberOfLines = 100
self.view.addSubview(responseLable)
//生成UI >>>>>>>>>>>>>>>>>>>>>
print("start http request...\n")
//要发送的请求数据
let json = [
//返回数据太长 "[]": [
"User": [
"sex": 1
]
//]
]
//请求URL
let url:NSURL! = NSURL(string: "http://39.108.143.172:8080/get")
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
//设置发送的数据格式为JSON
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch {
print("Something went wrong!")
}
//默认session配置
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
//发起请求
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) in
print("received result!\n\n")
print(data)
print(response)
print(error)
//数据类型转换
let jsonData:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
print(jsonData)
let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(jsonData, options: [NSJSONWritingOptions.PrettyPrinted]) as NSData!
let str = String(data: data, encoding: NSUTF8StringEncoding)
print("str = \n" + str!)
//显示返回结果
dispatch_async(dispatch_get_main_queue(), {
responseLable.text = "Response:\n" + str!
print("set text end\n\n")
});
}
//请求开始
dataTask.resume()
}
}