iOS实际上web请求参数中是可以传递中文和JSON的,只要对其进行转义就OK
但是一定要注意在请求地址的前面加上http://
1.先定义请求字符串,给字符串幅值,然后再用stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding将请求参数转义,然后再把字符串定义为NSURL
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text]; //转码 urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; // 2.创建请求对象 NSURLRequest *request=[NSURLRequest requestWithURL:url];
2.json传递时可以用字典
NSString *urlString = @"http://192.168.1.53:8080/MJServer/login"; NSDictionary *param = @{@"phone":@""}; urlString = [urlString stringByAppendingString:[self toJSONString:param]]; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"hhhhh......%@",urlString); NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"GET"]; [urlRequest setTimeoutInterval:30.0f]; NSLog(@"哼哼。。%@",urlRequest); NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if ([data length] > 0 && connectionError == nil) { NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"呵呵。。。%@",html); } else if ([data length] == 0 && connectionError ==nil ) { NSLog(@"Nothing was downloaded!"); } else { NSLog(@"%@",connectionError); } }]; }//这个函数就是将字典封装成转义的JSON字符串- (NSString *)toJSONString:(NSDictionary *)dict{ NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPRettyPrinted error:&error]; NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; str = [NSString stringWithFormat:@"%@",str]; return str;}新闻热点
疑难解答