当发送网络请求: 确定请求路径URL 时, 观察url中是否包含中文, 如果包含中文 需要将url中的中文进行转码操作.
注意:
上面这种情况 只针对于发送GET请求,因为GET请求的URL 包含用户名和密码. POST请求的用户名和密码 在请求体信息中. 在请求体信息中 包含中文也无须做 中文转码操作.
总结:
查看请求路径URL中是否包含中文, 如果包含中文 需要做中文转码.
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
#pragma mark ----------------------
#pragma mark Events
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self get];
}
#pragma mark ----------------------
#pragma mark Methods
-(void)get
{
NSString *urlStr = @"http://localhost:8080/MJServer/login?username=123&pwd=朝阳&method=get&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://localhost:8080/MJServer/login";
//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=123&pwd=朝阳&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
注意观察: 上面发送GET请求中,请求路径中包含 中文字符. 因此需要转码.
不转码的控制台打印:
转码后的打印: