iOS网络编程HTTP解决方案-NSURLConnection-百分号转码

GET方法:

- (void)get{
    NSString *urlStr = @"http://www.jianshu.com/users/iOS程序员";
    // 将中文URL进行转码
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                // 解析服务器返回的数据(解析成字符串)
                                NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                NSLog(@"%@", string);
                            }];
}

POST方法:

- (void)post{
    NSString *urlStr = @"http://www.jianshu.com/users/login";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // 百分号转码
    request.HTTPBody = [@"username=iOS程序员&pwd=密码" dataUsingEncoding:NSUTF8StringEncoding];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                // 解析服务器返回的数据(解析成字符串)
                                NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                NSLog(@"%@", string);
                            }];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容