As a best practice all the HTTP requests to get some data or perform an operation over the network should be done in an Asynchronous way (separate thread) to avoid the GUI be non-responsive and not freeze while the http client is waiting for the response from the remote end. This can be accomplished by creating a separate thread and doing the sync request/response there or easily using a library like ASIHTTP that would abstract that for you. <!--break-->
Asychornous Http Request with ASIHTTP
- -(void) sendAndCallBack:(NSString *) restUrl withCallBack:(NSObject*) delegate
- {
- debugLog(@"in :sendAndCallBack");
- ASIHTTPRequest *request =[ASIHTTPRequest requestWithURL:[NSURL URLWithString:restUrl]];
- [request setDelegate: delegate];
- [request setTimeOutSeconds:REQUEST_TIMEOUT];
- [request setAllowCompressedResponse:NO];
- [request setDefaultResponseEncoding:NSUTF8StringEncoding];
- [request startAsynchronous];
- NSError *error =[request error];
- if(!error){
- NSString *response =[request responseString];
- debugLog(@"Content %@",response);
- NSString *contentLength =[[request responseHeaders] objectForKey:@"Content-Length"];
- for(id key in [request responseHeaders]){
- NSLog(@"key: %@, value: %@", key, [[request responseHeaders] objectForKey:key]);
- }
- debugLog(@"Content %@",contentLength);
- int cl =[contentLength intValue];
- int begin =[response length]- cl;
- debugLog(@"Content begin %d Length %d",begin ,cl);
- response =[response substringWithRange:NSMakeRange(begin, cl)];
- debugLog(@"Response %@",response);
- }
- }