#GET
// 0.请求路径
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://120.25.226.186:32812/login?username=%@&pwd=%@", username, pwd]];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 4.回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// 隐藏HUD
// [SVProgressHUD dismiss];
}];
}];
#POST
// 1.请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
// 2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 更改请求方法
request.HTTPMethod = @"POST";
// 设置请求体
request.HTTPBody = [@"username=jack&pwd=jack" dataUsingEncoding:NSUTF8StringEncoding];
// 设置超时(5秒后超时)
request.timeoutInterval = 5;
// 设置请求头
// [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
// 3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) { // 比如请求超时
NSLog(@"----请求失败");
} else {
NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
#中文URL进行转码
// 0.请求路径
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=张三&pwd=123456";
// 将中文URL进行转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
request.HTTPBody = [@"username=张三&pwd=123456" dataUsingEncoding:NSUTF8StringEncoding];