IOS HTTP GET POST学习笔记
来源:互联网 发布:无缝贴图软件 编辑:程序博客网 时间:2024/05/16 12:39
NSString *urlStr = [NSStringstringWithFormat:@"http://192.168.1.104:8080/MJServer/login?username=%@&pwd=%@", username, pwd];
// 转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// URL里面不能包含中文
NSURL *url = [NSURL URLWithString:urlStr];
// 2.2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
request.timeoutInterval = 5; // 设置请求超时
// 2.3.发送请求
[self sendAsync:request];
NSLog(@"---------已经发出请求");
/**
* 发送异步请求的方式1: 类方法, block
*/
- (void)sendAsync:(NSURLRequest *)request
{
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queuecompletionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)
// 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程)
[MBProgressHUD hideHUD];
/**
解析data :
{"error":"用户名不存在"}
{"error":"密码不正确"}
{"success":"登录成功"}
*/
if (data) { // 请求成功
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) { // 登录失败
[MBProgressHUD showError:error];
} else { // 登录成功
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
} else { // 请求失败
[MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
}
}];
}
/**
* 发送异步请求的方式2: start方法, 代理
*/
- (void)sendAsync2:(NSURLRequest *)request
{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:requestdelegate:self];
[conn start]; // 异步执行
}
POST 方法
// 2.2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
request.timeoutInterval = 5; // 设置请求超时
request.HTTPMethod = @"POST"; // 设置为POST请求
// 通过请求头告诉服务器客户端的类型
[request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
// 设置请求体
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
- IOS HTTP GET POST学习笔记
- iOS-Http : GET : POST
- iOS开发笔记>> socket, http(post, get), TCP/ IP
- iOS http get和post
- iOS http get和post
- iOS http访问post 、get
- android学习笔记之HTTP GET/POST传递参数
- iOS GET&POST对比~笔记
- iOS http get和post(2)
- iOS http get和post(3)
- IOS开发 HTTP相关GET/POST请求
- ios发送http GET和POST请求
- iOS HTTP协议的get,post方法
- iOS http get和post(2)
- iOS http get和post(3)
- iOS原生Http请求,get post 异步
- java鬼混笔记:http get post 请求
- HTTP协议学习,post于get
- POJ2752 Seek the Name, Seek the Fame(kmp)
- JS点名神器
- php获取内容中的所有图片
- POJ3461 Oulipo(kmp)
- Java 基本类型 long 的一些使用陷阱
- IOS HTTP GET POST学习笔记
- 迅雷 API 接口说明文档 -调用迅雷自动下载
- HTTP协议规定的 - URL中的保留字符
- 手势识别器
- Unity的Socket通讯_3_粘包丢包
- scanf不判断是否读到EOF导致 output limit exceed
- *LeetCode-Scramble String
- FZU 2198 快来快来数一数 (dp + 矩阵快速幂)
- AX 2012 上线杂记 二