how to consume the json web service in objective c? - objective-c

i am consuming the json webservice .i am assigning the stringurl to nsurl but the nsurl always assigning the null value. also i didn't get the response. can anyone suggest me what is the mistake i done in the following coding
- (IBAction)addbutton:(id)sender {
NSString *urltest = #"sample url";
NSURL *url = [NSURL URLWithString:urltest];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSString *test= [[greeting objectForKey:#"code"] stringValue];
NSString *test1 = [greeting objectForKey:#"message"];
}
}];}

Your URL string is invalid, note the part:
taxName=ÂU.F¿Kåa¥gh
Those characters are not allowed in URL. Fix your URL to a valid URL (e.g. percent-encode parameter values).
E.g. the above with URL encoding would be:
taxName=%C3%82U.F%C2%BFK%C3%A5a%C2%A5gh
but I am not sure that's correct. The parameter value does not seem to be valid.

Please use this:
NSString *urlString = #"http://localhost:8080/MyWebservice.asmx/GetHelloWorldWithParam";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *myRequestString = #"param="; // Attention HERE!!!!
[myRequestString stringByAppendingString:myParamString];
NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
[request setHTTPBody: requestData];
Thank you

Related

How to send json data in the Http request to POST Method in JSON Parsing

I need to Parse below string to POST method in iOS
"jsonData":{"empId":"cxvd","password":"sfsd"}
But I m getting the error as
Res: Tomcat Error
HTTP Status 400 - Required String parameter 'jsonData' is not present
//------ Method I have used to Parse is ---------- //
+(void) requestToServerForLogin:(NSString*)userName andPassward: (NSString*)password onCompletion:(RequestCompletionHandler) handler
{
NSString *url = [Ip stringByAppendingString:#"login"];
NSString *jsonString = [NSString stringWithFormat:#"\"jsonData\":{\"empId\":\"%#\",\"password\":\"%#\"}",
userName,
password ];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:nsurl];
[urlRequest setTimeoutInterval:60.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json"
forHTTPHeaderField:#"Content-type"];
NSString *body = jsonString1;
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"urlRequest :%#",[body dataUsingEncoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data1, NSError *error)
{
NSString *res = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
if(handler) handler(res,error);
}];
}
Thanks in advance
There is way to much code. The substringToIndex and substringFromIndex are wrong, should not be in the code.
Use the literal syntax for the dictionaries:
NSDictionary *jsonDict = #{#"jsonData":#{#"password":password, #"empId":userName}};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

sending files to server and receiving feedback

I have this code who send a file to my server:
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://websitetester.com/here.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSLog(#"File Send to server!");
this code works perfectly but I would like to receive a return from the server, the php file at the end of the code I show:
<?php
if(...){
...
echo "Data Received";
}else{
...
echo "Error in server";
}
?>
All I'm trying is receive this echo in php and show an alert inside my app, how code I can implement inside my code to do that?
EDIT
Hey I find a code who receive the return data in objetive-c, the code is:
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);
and now the code works the way I expected.

NSMutableURLRequest returns old values even cachePolicy is NSURLCacheStorageNotAllowed

Im using codes posted here:
connection release method in connectionDidFinishLoading, causes error
now first execute returns didFail log.
second execute; returns old response data.
albeit my (localhost) server is totally offline.
and cachePolicy is NSURLCacheStorageNotAllowed (check the code on the link I posted above)
NSMutableURLRequest *request=
[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f];
the response data seems cached somewhere and still exists.
but if I use NSURLRequestReloadIgnoringLocalAndRemoteCacheData //which is commented as -not implemented-
not returns old cache.
but if so what is the difference between:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData
and
NSURLCacheStorageNotAllowed
what shall I do ?
NSURLCacheStorageNotAllowed refers to NSCachedURLResponse and is an value of enum NSURLCacheStoragePolicy. Since the cache policy of NSMutableURLRequest is also an enum (NSURLRequestCachePolicy) you just pass wrong int to the static method creating NSMutableURLRequest. In this case NSURLCacheStorageNotAllowed is just 2 which equals to NSURLRequestReturnCacheDataElseLoad - and that is why you get old data.
Try This
NSString *Post = [[NSString alloc] initWithFormat:#"Post Parameters"];
NSURL *Url = [NSURL URLWithString:#"Url"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [PostData length]];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:#"POST"];
[Request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[Request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[Request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[Request setHTTPBody:PostData];
NSError *error;
NSURLResponse *response;
NSData *Result = [NSURLConnection sendSynchronousRequest:Request returningResponse:&response error:&error];
if (!Result)
{
NSLog(#"Error");
}
else
{
//Parse the result
}

Vimeo.com upload failure

To have an ability to upload i have to get upload ticket. But after checking it looks like invalid.
After I create new ticket I check it and get the error 702. Please help. i've checked the parameters and they looks fine.
//vimeo.videos.upload.getTicket
NSURL *ticketRequestURL = [NSURL URLWithString:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.getTicket"];
NSMutableURLRequest *ticketRequest = [NSMutableURLRequest requestWithURL:ticketRequestURL];
[ticketRequest setHTTPMethod:#"POST"];
[auth authorizeRequest:ticketRequest];
[NSURLConnection sendAsynchronousRequest:ticketRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *ticketRequestResponse, NSData *ticketRequestData, NSError *ticketRequestError) {
NSString *ticketRequestResponseString = [[NSString alloc] initWithData:ticketRequestData encoding:NSStringEncodingConversionAllowLossy];
NSDictionary *d = [[parser objectWithString:ticketRequestResponseString] objectForKey:#"ticket"];
NSString *identifier = [d objectForKey:#"id"];
//vimeo.videos.upload.checkTicket
NSURL *ticketCheckRequestURL = [NSURL URLWithString:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.checkTicket"];
NSMutableURLRequest *ticketCheckRequest = [NSMutableURLRequest requestWithURL:ticketCheckRequestURL];
[ticketCheckRequest setHTTPMethod:#"POST"];
[ticketCheckRequest setValue:identifier forHTTPHeaderField:#"ticket_id"];
[auth authorizeRequest:ticketCheckRequest];
[NSURLConnection sendAsynchronousRequest:ticketCheckRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *ticketRequestResponse, NSData *ticketRequestData, NSError *ticketRequestError) {
NSString *ticketCheckRequestResponseString = [[NSString alloc] initWithData:ticketRequestData encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"%#", ticketCheckRequestResponseString);
}];
}];
Hm... Specifying ticket_id in the URL solved my problem.
NSURL *ticketCheckRequestURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://vimeo.com/api/rest/v2?format=json&method=vimeo.videos.upload.checkTicket&ticket_id=%#", identifier]];

Can't POST a request to service

For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!
It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes
So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.