Network (二)

我是demo

上一篇通过 Node JS 和 NSURLSession 实现了简单的 GET 请求,这一篇实现 POST 请求

Server

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
var http = require('http')
var queryString = require('querystring')

//创建服务器
var server = http.createServer(function(req, res) {
console.log(req.url)
console.log(req.method.toLocaleLowerCase())
if (req.method.toLocaleLowerCase() === 'post') {

var alldata = ''
req.on('data', function(chunk) {
alldata += chunk
})

req.on('end', function() {
res.end('Success')
var dataString = alldata.toString()
var dataObjc = queryString.parse(dataString)
console.log(dataObjc)
console.log(dataObjc.username)
console.log(dataObjc.password)
})

}
})


server.listen(9000, function() {
console.log('server is running ')
})

Server 地址: http://127.0.0.1:9000
POST 请求格式: username=’maple’&password=’xxxx’

Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)update {

//构造 Request 对象,设置 url 和 POST 请求方法 以及请求体
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:9000"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[@"username=maple&password=xxx" dataUsingEncoding:NSUTF8StringEncoding]];
//构造网络请求
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@ %@ %@ %@", data, response, error, [NSThread currentThread]);
}];
//启动任务
[task resume];
}

这里是通过 NSURLSession 实现 POST 请求,所以需要做的事情有:

  1. 创建可变的请求对象;
  2. 设置 url requestWithURL:
  3. 设置请求方法 setHTTPMethod:
  4. 设置请求体:setHTTPBody:
  5. 创建 session,通过 shareSession 单例实现;
  6. 通过 dataTaskWithRequest: completionHandler: 实现网络构造;
  7. resume 启动

Process

当客户端发起请求的时候,在 Node 服务端,通过

1
2
3
console.log(dataObjc)
console.log(dataObjc.username)
console.log(dataObjc.password)

输出:

1
2
3
{ username: 'maple', password: 'xxx' }
maple
xxx

结束,这就是一个完整的 POST 请求过程

-------------本文结束谢谢欣赏-------------
Alice wechat