您当前的位置: 首页 >  网络

white camel

暂无认证

  • 0浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

iOS开发网络篇 一一 请求路径(URL)中文转码问题

white camel 发布时间:2017-12-17 13:10:13 ,浏览量:0

当发送网络请求: 确定请求路径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请求中,请求路径中包含 中文字符. 因此需要转码.

不转码的控制台打印: 

转码后的打印:

关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0409s