I tried to add an entry to db using a POST request in Objectve-C. My service is:
#RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
#ResponseBody
boolean addEmployee(#ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
When I try this on Postman, it's working fine with x-www-form-urlencoded. But when I try this in Objective-C, nothing happens. Here is what I tried:
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[rq setValue:[NSString stringWithFormat:#"%ld", (long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"%#", [error localizedDescription]);
}];
In completion block, the log prints "Could not connect to the server". How can I call the service with JSON data?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"%#", json);
success(json);
}];
[dataTask resume]; // Executed First
Related
I am working in an application in which I have to send image to the server, I am trying to send Image to server but in return I am getting
BAD REQUEST 400
. Please tell me how do I resolve this error.
This method is use to convert image into base64 string
NSData * imagedata = UIImageJPEGRepresentation(chosenImage, 0.5);
NSString * base64String = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength
-(void)temp
{
NSString * str=[self base64return];
NSDictionary* jsonDict = #{
#"name": #"image_name",
#"img_data":str
};
NSData * postData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:kNilOptions error:nil];
NSURL * url=[NSURL URLWithString:#"http://xxxxxx/finalresult1"];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (error == nil)
{
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
NSString * text = [[NSString alloc] initWithData: data encoding:
NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSLog(#"erroer is %#",error);
}
else
{
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
Change request Content-Type, Use:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
hello all i know this kind of question asked previously but i didn't get any solution from them
in my project i am working in login view when i am put code on login button i am getting an error
Error : Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x7fb37b62c9a0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x7fb37b715a20 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1002.)"}
but i am using the same code for login which i used in my previous projects and it works fine there
here is my code:
-(IBAction)login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php?token={LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUc4d0RRWUpLb1pJaHZjTkFRRUJCUUFEWGdBd1d3SlVBeWo0WE9JNjI4cnJRTG9YeEpXNG1zUWI1YmtvYk1hVQpzMnY1WjFKeXJDRWdpOVhoRzZlZk4rYTR0eGlMTVdaRXdNaS9uS1cyL1NCS2pCUnBYUzVGYUdiV0VLRG1WOXkvCkYrWHhsUXVoeER0MEV3YkRBZ01CQUFFPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K}&method=user.getLogin"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"login=abc#gmail.com&password=123456"];//,username.text, password.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"map data is = %#",mapData);
NSURLSessionDataTask * postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse* response, NSError * error) {
if(error == nil)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"jsondic= %#",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:#"data"];
NSLog(#"Dict is %#",userDataDic);
Please help me to resolve it i already see the similar type of questions but didn't overcome from this issue
Any help is appreciated
I tried your code.Except your url the other lines of code is correct.If you pass your corrct URL,it works perfectly.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php"]]; //pass your url here
[request setHTTPMethod:#"POST"];
//Passing The String to server
NSString *strUserId = #"pradeep.kumar#eyeforweb.com";
NSString *strPassword = #"admin123";
NSString *userUpdate =[NSString stringWithFormat:#"login=%#&password=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is %#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"The postData is - %#",data1);
//Apply the data to the body
[request setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
I'm trying to post new data to a ws but im geting error each time
I need to
1-pass a username and password each time
2-code the data with AES256 WITH THE API KEY
Code:
- (IBAction)AddTicket:(id)sender {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *URL = [[NSURL alloc] initWithString:#"http://dev.enano-tech.com/api/Ticket"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"1",#"idProject",#"1",#"idTicketType",#"nameo",#"name",#"nameo",#"description", #"1",#"idStatus",#"2016-06-23 15:20:49",#"creationDateTime", nil];
NSData *dataToPost = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSData *final =[dataToPost AES256EncryptWithKey:#"02b6e206868660a0d59d2e51a11fdcd6"];
//
NSLog(#"postData1e == %#",final);
NSLog(#"final %#",dataToPost);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request addValue:#"CURLAUTH_BASIC" forHTTPHeaderField:#"CURLOPT_HTTPAUTH"];
[request addValue:#"Basic YWRtaW46YWRtaW5hZG1pbg==" forHTTPHeaderField:#"authorization"];
[request addValue:#"admin:adminadmin" forHTTPHeaderField:#"CURLOPT_USERPWD"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_RETURNTRANSFER"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_SSL_VERIFYPEER"];
[request addValue:#"POST" forHTTPHeaderField:#"CURLOPT_CUSTOMREQUES"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_POST"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_POSTFIELDS"];
[request setHTTPBody:final];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithData:final encoding:NSUTF8StringEncoding];
NSLog(#"data %#",data);
NSLog(#"respoce %#",response);
NSLog(#"result == %#",result);
}];
[postDataTask resume];
}
Response:
2016-08-02 15:06:47.768 Projector[3936:1619429] result == {"error":"invalid API query", "message":"'data' is not correctly encoded for method POST. Request for correct API KEY"}
this is the documentation of api:
enter image description here
Your webserver is missing "data" from the website. To fix it, you'll need to add that field to your form or find the correct field name (case sensitive)
I have tried this methods, I want to know about integration of rest API in iOS.
I want to know about JSON parsing in web services. I know about these methods but how to use it? but what is function of each method?
This IBAction method sends request string for signup to the server .
-(void)genSignup
{
responseData = [NSMutableData data];
urlLoc= [urlLoc stringByAppendingString:service];
NSLog(#"%#",requestString);
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//NSLog(#"%#",request);
PostConnectionRegisterGenUser = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[MyClass removePregressIndicator:self.view];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[MyClass removePregressIndicator:self.view];
if (connection == PostConnectionRegisterGenUser)
{
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}
}
how to use it?
NSURLConnection is deprecated effective Mac OS 10.11 and iOS 9. So, at this point NSURLSession should be used instead of NSURLConnection.
I just add NSURLSession in your code. Change Key, URL accordingly. I did not compile it.
NSString * requestString = [NSString stringWithFormat:#"Name=%#&Email=%#&Password=%#&MobileNumber=%#&BloodGroup=%#&DeviceID=%#&City=%#&DeviceType=I",txtName.text,txtEmail.text,txtPassword.text,txtMobileno.text,strBlood,strDeviceID,txtCity.text];
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{ #"api-key": #"API_KEY"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask *sessionPostDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// The server answers with an error because it doesn't receive the params
}];
[sessionPostDataTask resume];
Do let me know if you need any other information.
Hope this will help you !!!
Use simple common methods for NSURLSession WS Calling.
-(void)callWebserviceWithParams:(NSDictionary *)aParams withURL:(NSString *)aStrURL withTarget:(UIViewController *)aVCObj withCompletionBlock:(void(^)(NSMutableDictionary *aMutDict))completionBlock withFailureBlock:(void(^)(NSError *error))failure
{
NSString *aStrParams = [self getFormDataStringWithDictParams:aParams];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
aStrURL = [aStrURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:aStrURL]];
[aRequest setHTTPMethod:#"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
aMutDict = [aMutDict dictionaryByReplacingNullsWithBlanks];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
[postDataTask resume];
}
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:#""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:#"%#=%#&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = #"";
return aStrParam;
}
Use Like This
NSDictionary* param = #{
#"Key1":#"Value1",
#"Key2":#"value2"
};
[self callWebserviceWithParams:param withURL:#"URL String" withTarget:self withCompletionBlock:^(NSMutableDictionary *aMutDict) {
//code For Success
} withFailureBlock:^(NSError *error) {
// code for WS Responce failure
}];
also you have to set this method in NSObject Class and make it simple and used in whole app.
Another option Nsurlsession:
-(void)Fetchdata
{
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:#"http://52.2/category_list.php"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = #"admin_id=19";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",results);
arryTempdata = [[results valueForKey:#"message"] valueForKey:#"banner"];
NSLog(#"%#",arryTempdata);
tblV.reloadData;
}];
// Fire the request
[dataTask resume];
}
I am fetching data using POST method. And I have successfully retrieved all the data.It's taking too long to display it in UI but I can print it immediately on console, my code is
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.xxxyyy.com/v1/api/client/authorize"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"ABCD" forHTTPHeaderField:#"Authkey"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Authkey"];
NSData* data1 = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingAllowFragments error:&error];
NSArray *array = [jsonReturnArray copy];
[self rec:array];
NSString *phoneNumber=[NSString stringWithFormat:#"%#",[jsonReturnArray valueForKey:#"phone"]];
lblPhoneNumber.text = phoneNumber;
NSString *Address=[NSString stringWithFormat:#"%# %# %#,CA %#",[jsonReturnArray valueForKey:#"street1"],[jsonReturnArray valueForKey:#"street2"],[jsonReturnArray valueForKey:#"city"],[jsonReturnArray valueForKey:#"postalcode"]];
lblAddress.text=Address;//takes long time to display
NSLog(#"%#",Address);//immeaditely print
strlatitude=[jsonReturnArray valueForKey:#"latitude"];
strlongitude=[jsonReturnArray valueForKey:#"longitude"];
[self Map:(MKMapView *)mapLocation didUpdateUserLocation:(MKUserLocation *)nil];//method call
}] resume];
This is take too time to print data, but if you use NSURLConnection class it may be help you.This is my Class method it may be helpful.
+ (void)postRequestData:(NSDictionary *)postVars
Action:(APIMode)action
WithCompletionHandlar:(void (^) (id result, BOOL status))completionBlock
{
NSURL *url = [NSURL URLWithString:API_URL([self getAPINameForType:action])];
NSLog(#"Request URL %#",[NSString stringWithFormat:#"%#",url]);
NSString *contentType = #"application/json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *err = nil;
NSMutableDictionary *params=[[NSMutableDictionary alloc] initWithDictionary:postVars];
// [params setObject:[self getAPINameForType:action] forKey:#"mode"];
NSLog(#"Paramater %#",params);
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)body.length] forHTTPHeaderField: #"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(!connectionError)
{
NSError *error = nil;
NSDictionary *dictResponse = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error]];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(dictResponse,(error == nil));
});
NSLog(#"%#",dictResponse);
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(connectionError.localizedDescription,NO);
});
}
}];
}
Use this method instead of it.It is executed fast because NSURLConnection Class execute in background.
Try to fetch your data using NSURLConnection class(manual code) or simply use AFNetworking class(less code). AFNetworking internally uses NSURLConnection class itself.