iOS - OC - 网络请求 - 中文转码
2024-08-21 02:32:41
#import "ViewController.h" @interface ViewController () @end @implementation ViewController #pragma mark ----------------------
#pragma mark Events
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self post];
} #pragma mark ----------------------
#pragma mark Methods
-(void)get
{ NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it&type=JSON"; NSLog(@"转码前: %@",urlStr); //中文转码处理:请求接口有中文
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"转码后: %@",urlStr); //1.url
NSURL *url = [NSURL URLWithString:urlStr]; //http://120.25.226.186:32812/login2?username=%E5%B0%8F%E7%A0%81%E5%93%A5&pwd=520it&type=JSON NSLog(@"url------%@",url); //2.urlrequest
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.connect
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //容错处理
if (connectionError) {
NSLog(@"%@",connectionError);
return ;
}
//4.解析
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}]; } -(void)post
{
//观察URL中是否有中文,如果有中文则需要转码
NSString *urlStr = @"http://120.25.226.186:32812/login2"; //username=小码哥&pwd=520it&type=JSON
//1.url
NSURL *url = [NSURL URLWithString:urlStr]; //2.urlrequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //2.1 post
request.HTTPMethod = @"POST"; //2.2 body
request.HTTPBody = [@"username=小码哥&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding]; //3.connect
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //容错处理
if (connectionError) {
NSLog(@"%@",connectionError);
return ;
}
//4.解析
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}]; }
@end
最新文章
- Linux 安装node.js ---- 源码编译的方式
- 【C语言学习】《C Primer Plus》第5章 运算符、表达式和语句
- Aoite 系列(04) - 强劲的 CommandModel 开发模式(上篇)
- 常用的HTML标签
- nginx的请求接收流程(二)
- Windows Azure 社区新闻综述(#68 版)
- mfc添加气球式提示栏
- java学习之总结
- css技巧总结
- TDE: Transparent Data Encryption brief introduction
- Android Button常用法
- tensorflow tfrecord文件存储
- mysql之事务管理
- mtd工具
- canvas学习之粒子动画
- [PHP]PHP自定义遍历目录下所有文件的方法
- 【原创】backbone1.1.0源码解析之View
- NGINX域名跳转案列
- 进度条(Progressbar)
- vs删除空行 —— 正则表达式以及其他