-JSONValue failed. Error is: Unexpected end of input - iphone

I got the JSON result as -JSONValue failed. Error is: Unexpected end of input. Please direct me in right way.
I am new in parsing . I have to get Data from the server by POST method. I have following details. I have to pass zip with url
{"zip":"52435","methodIdentifier":"search_dealer"}
url : http://usaautoleads.com/api.php
method: post
web service name: search_dealer
response : {"success":"0","dealer":[info...]}
my code is here.
NSURL *myURL=[NSURL URLWithString:#"http://usaautoleads.com/api.php"];
NSString *post =[[NSString alloc]initWithString:#"52435"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setURL:myURL];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

The problem here is with your post string. Use this one
NSString *zip = #"52435";
NSString *methodID = #"search_dealer";
NSString *post =[NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"%#\"}", zip, methodID];

Related

Login credential issue using NSURL Methods

I have an webservices url which appends with password. When I run the application by giving correct password, the application is running and at the same time when I run the app with wrong credentials. the app is running, I didn't have an idea to get rid out of the issue. My code is here:
NSString *post =[[NSString alloc] initWithFormat:#"password=%#",[password text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/Accountservice/Secure/ValidateAccess?password=abcd&type=1"]];
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];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:post] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self startImmediately:YES];
if(!connection){
NSLog(#"connection failed");
}
else{
NSLog(#"connection succeeded");
}
If I gave 'abcd' as password connection is successfully is displaying. If I gave wrong password connection successfully is displaying. How can I solve the issue? If I gave wrong password need to display an alert.
This control structure here is the problem:
if(!connection){
NSLog(#"connection failed");
}
else {
NSLog(#"connection succeeded");
}
This doesn't check for a bad connection, this checks whether or not the connection object is equal to 0 (nil). Obviously, having initialized it on the line above, the else statement will always log, giving you the false impression that your connection had succeeded. You should become the connection's delegate, and respond to the appropriate delegate methods instead.
The issue may be with the url you are using
Fire the url in the browser and see what it returnes
try add the url params with single quotes accesscode='abcd'
It is not a good practice to pass the credentials via this way.
You could use POST method with some valid encryption to prevent the security issues that can occur
SOLUTION
Try this
NSString *urlString=#"http://myexample.com/Accountservice/Secure/ValidateAccess?";
self.responseData = [NSMutableData data];
NSString *post =[NSString stringWithFormat:#"username=%#&password=%#",userNameTextField.text,passwordTextField.text];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection0= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection0 start];

JSON parsing, How to get response from server

I have the following details, for get the data from server. What is the use of methodIdentifier and web service name ?
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
I don't know how to send zip number "12345" with the url. Please direct me on right direction. I use the following.
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
when i print the response in console :\"Unexpected end of string\"
Without knowing more about the API, I can't be certain about your requirements, but it seems that the server is expecting the request to contain JSON. The way you currently are creating the body for the request is using standard POST variables.
Have you tried changing:
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
to:
NSString *post = [NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
Regarding your other questions, I'm guessing that there is a single URL for the API. The methodidentifier is used by the server in order to determine which server method(s) to run.
You get this error because you do not get a json as a response, but an error from Apache (or whatever), that has different structure, and json cannot parse it. Try my method to initiate the connection, in order to gain a successful one.
Declare a NSURLConnection property and synthesize it. Now:
NSString *post = [NSString stringWithFormat:#"zipNumber=%#",zipNumber];
NSString *toServer = [NSString stringWithString:#"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
Now you work with self.yourConnectionProperty in connection delegates. Cheers!
hey bro check my answer for same problem may help you... You have to use the NSURLConnection Delegates to get the data
Could not make Json Request body from Iphone

xml parsing with Post method+iphone

I am having problem with xmlparsing with post method.
API URL : http://XXX.XXX.X.XX/api/user.php
Function Name : getUserList
Sample XML :
<root>
<data>
<id>0</id>
<search></search>
</data>
</root>
Now i am using :-
// setting up the URL to post to
NSString *urlString = #"http://XXX.XXX.X.XX/api/user.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
But how should i make the post HTMLbody part in this..
Means where and how should i put functional name and sample xml in the code
My Edited Question is :-
NSString *urlString = #" http://192.168.6.79/silverAPI/api/user.php/getUserList";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString * str = #"<root><data><id>0</id><search>a</search></data></root>";
NSString * message= [NSString stringWithFormat:#"/getUserList mydata=%#", str];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Responce==>%#",returnString);
But i getting black in responce.Pleaseee help me out..
is my
NSString *urlString = #" http://192.168.6.79/silverAPI/api/user.php/getUserList";
And
NSString * str =
#"0a";
NSString * message= [NSString stringWithFormat:#"/getUserList
mydata=%#", str];
[request setHTTPBody:[message
dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:#"application/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
This part of code is correct??
You can set html body using method - (void)setHTTPBody:(NSData *)data. For example:
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
where message is,in your case, xml.
Also you need to add this code to help server to determine type of sent data:
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
If you want to set some additional flags to your request you can use method - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field.
What you have done is perfect, please check on server side whether response from there is coming properly by sending the same request or not.

How to set the format of JSON post method in iphone

I'm sending a post request through webservices but I'm not getting the response I want.
Here's my code:
NSString *newurlString = [NSString stringWithFormat:#"{\"name\":\"asit\",\"email\":\"m.kulkarni#easternenterprise.com\",\"businessType\":\"1\",\"score\":30}"];
NSString * url = #"http://www.nieuwe-dag.nl/mobile_be/public/?action=saveScore";
//NSString *urlString =[NSString stringWithFormat:#"name=%#&email=%#&businessType=%d&score=%d",name, email, bussinesstype, score];
NSData *postData = [newurlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"urlString::%#",newurlString);
NSLog(#"postLength::%#",postLength);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection){
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"theConnection is NULL");
}
You are setting the request type to json but you are not creating a json. The data you are creating is just nsstring. I think you need to create a json object. You can download JSON API from here:
https://github.com/stig/json-framework/
Use [SBJSONWriter dataWithObject:] to create a JSON object. Then pass it to your request.
FOr more info on JSON:
http://www.json.org/
You need proper postData
NSDictionary *dataDict = #{
#"name": #"asit",
#"email": #"m.kulkarni#easternenterprise.com",
#"businessType": #"1",
#"score": #(30)
};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];

Why this POST don't work?

this is my snippet:
NSString *post = #"from=A&name=B&email=ciccio#aaasd.com&messaggio=MESSAGE&codHidden=-1";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.mysite.com/page.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Succeeded! Received %d bytes of data",[urlData length]);
NSString *outputdata = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(#"%#", outputdata);
It call a php page that send me an email...
Is there any errors in this code?
Does not seem to work...
thanks
Is it a Synchronous/Asynchronous problem? If so, use the delegate-pattern and access the data asynchronously. Could you post any errors you see (or the server's response string)?
EDIT: Since you're not doing anything useful with the error returned, change your class to do the request asynchronously. A great answer to this was previously posted here. Once you implement didFailWithError you'll have a better picture.
Try to change NSASCIIStringEncoding to NSUTF8StringEncoding