Use of NSURLConnection, nsurlconnection
I. NSURLConnection (IOS9.0 has been deprecated) is an early http access method provided by apple. The following lists common scenarios: GET requests, POST requests, and Response with json data.
Note the following for NSURLConnection: (1) sendAsynchronourequest: queue: completionHandler: the queue parameter in the function indicates that "the handler block runs in the queue. If the queue is mainThread, then hanlder runs in the main thread. Therefore, pay attention to this parameter when processing the UI"
(1) Get request (response text)
// Request NSMutableURLRequest * urlRequest = [NSMutableURLRequest new]; [urlRequest setURL: [NSURL URLWithString: @ "http://XXX.sinaapp.com/test/test.php? Namr & id = 43 "]; [urlRequest setTimeoutInterval: 10.0f]; [urlRequest setHTTPMethod: @" GET "]; [urlRequest setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [NSURLConnection failed: urlRequest queue: queue completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError ){
// Based on the response Headers, check whether the object is NSHTTPURLResponse if ([response isKindOfClass: [NSHTTPURLResponse class]) {NSHTTPURLResponse * resHttp = (NSHTTPURLResponse *) response; NSLog (@ "status = % ld", resHttp. statusCode); // 200 304 401 ...... NSDictionary * dicHeader = resHttp. allHeaderFields; NSLog (@ "headers = % @", dicHeader);} else {NSLog (@ "not http ");}
If (data) {NSString * html = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", html) ;}}];
(2) POST request (response text)
// Request Parameters * urlRequest = [NSMutableURLRequest new]; [urlRequest setURL: [NSURL URLWithString: @ "http://XXX.sinaapp.com/test/test.php"]; [urlRequest setTimeoutInterval: 10.0f]; [urlRequest setHTTPMethod: @ "POST"]; [urlRequest setCachePolicy: Authorization]; NSString * strBody = @ "p1 = abc & p2 = 12"; [urlRequest setHTTPBody: [strBody dataUsingEncoding: NSUTF8StringEncoding]; NSOperationQueue * queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest: urlRequest queue: queue completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// confirm that it is http if ([response isKindOfClass: [NSHTTPURLResponse class]) {NSHTTPURLResponse * resHttp = (NSHTTPURLResponse *) response; NSLog (@ "status = % ld ", resHttp. statusCode); // 200 304 401 ...... NSDictionary * dicHeader = resHttp. allHeaderFields; NSLog (@ "headers = % @", dicHeader);} else {NSLog (@ "not http");} if (data) {NSString * html = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", html) ;}}];
(3) Response contains Json data
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSString *strBody = @"p1=abc&p2=12"; [urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSError *err2 = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2]; if([jsonObject isKindOfClass:[NSDictionary class]]){ NSLog(@"NSDictionary"); NSDictionary *dic = jsonObject; NSLog(@"dic = %@",dic); } else if([jsonObject isKindOfClass:[NSArray class]]){ NSLog(@"NSDictionary"); NSDictionary *arr = jsonObject; NSLog(@"arr = %@",arr); } }];
(4) Request data in Json format
// Request Parameters * urlRequest = [NSMutableURLRequest new]; [urlRequest setURL: [NSURL URLWithString: @ "http://XXXX.sinaapp.com/test/test.php"]; [urlRequest setTimeoutInterval: 10.0f]; [urlRequest setHTTPMethod: @ "POST"]; [urlRequest setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [urlRequest setValue: @ "application/json" forHTTPHeaderField: @ "Content-Type"]; // This sentence does not matter. NSDictionary * dicRequest = @ {@ "name": @ "leo", @ "id": @ "456 "}; NSData * jsonData = [NSJSONSerialization dataWithJSONObject: dicRequest options: callback error: nil]; [urlRequest setHTTPBody: jsonData]; optional * queue = [[callback alloc] init]; [NSURLConnection Timeout: urlRequest queue: queue completionHandler: ^ (response * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {NSError * err2 = nil; id jsonObject = [response failed: data options: NSJSONReadingAllowFragments error: & err2]; if ([jsonObject isKindOfClass: [NSDictionary class]) {NSLog (@ "NSDictionary"); NSDictionary * dic = jsonObject; NSLog (@ "dic = % @", dic);} else if ([jsonObject isKindOfClass: [NSArray class]) {NSLog (@ "NSDictionary "); NSDictionary * arr = jsonObject; NSLog (@ "arr = % @", arr) ;}}];
Server-side processing and return (add _ appending at the end of the request value, and then return)
<?phpheader('Access-Control-Allow-Origin:*');$json_string = $GLOBALS['HTTP_RAW_POST_DATA'];$obj = json_decode($json_string);//echo $obj->name;//echo $obj->id;$arr = array( "name"=>$obj->name."_appending", "id"=>$obj->id."_appending");echo json_encode($arr);
(5) download images from the server (the inspiration is that the common GET request only converts the data in response to the Image)
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"https://res.wx.qq.com/mpres/htmledition/images/pic/case-detail/nfhk_l23b6fe.jpg"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"GET"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { UIImage *img = [UIImage imageWithData:data]; [self.imgView setImage:img]; }];
(6) All the above actions can be done by proxy, and they are the same far away
NSURLConnectionDataDelegate,
NSURLConnectionDelegate,
NSURLConnectionDownloadDelegate