如果url中直接有中文,而不做任何处理的话,不会解析,返回为空。需要转码。
// 将中文URL进行转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
GET
- (void)get
{
// 0.请求路径
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";
// 将中文URL进行转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
// 1.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
}];
}
POST
- (void)post
{
// 0.请求路径
NSString *urlStr = @"http://120.25.226.186:32812/login2";
NSURL *url = [NSURL URLWithString:urlStr];
// 1.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=小码哥&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
// 2.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 3.解析服务器返回的数据(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
}];
}