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);
                            }];
}

你可能感兴趣的:(iOS网络编程HTTP解决方案-NSURLConnection-百分号转码)