#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self httpSendDataWithUrl:@"http://127.0.0.1/php/login.php" andUserName:@"zhang&san" andPsw:@"zhang"];
}
-(void)httpSendDataWithUrl:(NSString*)url andUserName:(NSString*)username andPsw:(NSString*)psw
{
//get请求的时候URL中的汉字空格,特殊字符不会进行编码,如果不自行编码,会出现错喔
NSString *name=username;
//oc 自带方法只会对空格汉字进行转义,不会转义特殊字符
name=[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//对特殊字符进行转义
name=[self encodeToPercentEscapeString:name];
NSString *pwd=psw;
NSString *httpUrl=url;
//----------------------Get方法的URL-------------
// NSString *str=[NSString stringWithFormat:@"?username=%@&password=%@",name,pwd];
// httpUrl=[httpUrl stringByAppendingString:str];
// NSURLRequest*request=[NSURLRequest requestWithURL:[NSURL URLWithString:httpUrl]];
//----------------------Get方法的URL-------------
//----------------------Post方法的URL和请求头-----------
NSMutableURLRequest *mRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:httpUrl]];
mRequest.HTTPMethod=@"post";
NSString *strBody=[NSString stringWithFormat:@"username=%@&password=%@",name,pwd];
mRequest.HTTPBody=[strBody dataUsingEncoding:NSUTF8StringEncoding];
//----------------------Post方法的URL和请求头-----------
[NSURLConnection sendAsynchronousRequest:mRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSError *error=nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error) {
NSLog(@"json解析错误!!!!!!");
}
else
{
NSLog(@"%@",json);
}
}else{
NSLog(@"服务器内部错误");
}
}else{
NSLog(@"请求错误%@",connectionError);
}
}];
}
//进行url编码 (但是不对汉字和空格进行编码)
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
NSString *outputStr = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)input,NULL,(CFStringRef)@"!*'();:@&=+ $,/?%#[]",kCFStringEncodingUTF8));
return outputStr;
}
//url解码
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
return [input
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
}
@end