NSURLConnection解析问题

时间:2014-09-05 10:28:38

标签: ios7 nsurlconnection ios7.1

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SPACEREQUESTFINAL_URL] cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"mymac", @"qerty!98"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:120];
[request  setAllHTTPHeaderFields:jsonDictionary];
NSHTTPURLResponse* urlResponse=nil;
NSError *error=nil;
NSData *serverResponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSLog(@"ServerResponse %@",serverResponse);
    if (error==nil)
    {
[NSURLConnection connectionWithRequest:request delegate:self];
NSString *str1=[[NSString alloc]initWithData:serverResponse encoding:NSUTF8StringEncoding];
NSLog(@"SSTR %@",str1);
NSMutableDictionary *JsonDict=[NSJSONSerialization JSONObjectWithData:serverResponse options:NSJSONReadingAllowFragments error:&error];
}

数据未解析 ServerResponse将为null - 请求不响应NSURLConnection可能

请建议如何解决。 谢谢

1 个答案:

答案 0 :(得分:0)

 NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setObject:[NSString stringWithFormat:@"%@", mymac] forKey:@"yourkeytoidentify"];
[datadict setObject:[NSString stringWithFormat:@"%@",qerty!98] forKey:@"yourkeytoidentify"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:@" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",string1);

}
}