IOS网络请求中文转码

本文详细介绍了iOS开发中如何使用GET与POST方法进行网络请求。包括了URL的构造、参数的设置、请求的发送及响应数据的解析等关键步骤,并通过具体的Objective-C代码示例展示了两种请求方式的具体实现。
-(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]);
    }];

}

 

转载于:https://www.cnblogs.com/sivek/p/6028034.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值