post request json parsing - iphone

question_id = 28, value = 'yes', null for now
then function will get
{
question_id = 22,
value = 'yes',
array = (9=>1, 28 => 0)
}
9 is id 1 for yes and 0 for no.
the array stores all previous questions and answers
and display the result if there is no question.
How do i implement/post/ this using two action buttons yes and no??

You can use the following code snippet, as described in this article:
Here, I simple describe how can use of POST method.
1. Set post string with actual username and password.
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
You need to send the actual length of your data. Calculate the length
of the post string.
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest
object and initialize it.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
Set the Url for which your going to send the data to that request.
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.abcde.com/xyz/login.aspx"]]];
Now, set HTTP method (POST or GET). Write this lines as it is in
your code.
[request setHTTPMethod:#"POST"];
Set HTTP header field with length of the post data.
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
Also set the Encoded value for HTTP header Field.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
Set the HTTPBody of the urlrequest with postData.
[request setHTTPBody:postData];
4. Now, create URLConnection object. Initialize it with the URLRequest.
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
It returns the initialized url connection and begins to load the data
for the url request. You can check that whether you URL connection
is done properly or not using just if/else statement as below.
if(conn)
{
NSLog(#”Connection Successful”)
}
else
{
NSLog(#”Connection could not be made”);
}
5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference.
Delegate methods are as below.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
Above method is used to receive the data which we get using post
method.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
This method , you can use to receive the error report in case of
connection is not made to server.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above method is used to process the data after connection has made
successfully.
Also Refer This and This documentation for POST method.
And here is best example with source code of HTTPPost Method.
EDITED:
-(void) buttonPressed:(id) sender
{
NSURL *url = [NSURL URLWithString:#"URL"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setShouldStreamPostDataFromDisk:YES];
[request setDidFinishSelector:#selector(uploadFinished:)];
[request setDidFailSelector:#selector(uploadFail:)];
[request setTimeOutSeconds:300];
[request setPostValue:#"Login" forKey:#"action"];
[request setPostValue:Yourvalue1 forKey:#"key1"];
[request setPostValue:Yourvalue2 forKey:#"key2"];
.
.
.
request.delegate = self;
[self.sendLoader startAnimating];
[request startAsynchronous];
}
#pragma Mark -
#pragma Mark - ASIHTTPRequest Methods
- (void) uploadFinished:(ASIHTTPRequest *)request
{
NSString *str = [request responseString];// convert it as JSON also.
}
- (void) uploadFail:(ASIHTTPRequest *)request
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Connection failed !!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show];
}

Related

Sending post variables to iOS form

I am trying to send a username and password to a website which is normally done through a form. The server however is redirecting me to a login page, which usually occurs when the username and password is wrong. The username is in the form of an email address and the password is a string.
I do currently have access to the website as the developer is away to check that the values are being processed correctly. Can anyone see any obvious errors in the code I have created below?
Please note I have removed the URL from the example code for privacy reasons.
// Validate login
-(bool)validateLogin{
// Initialize URL to be fetched
NSURL *url = [NSURL URLWithString:#"removedurl"];
NSString *post = #"username=example1%40example.com&password=example2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Initalize a request from a URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set url
[request setURL:url];
//set http method
[request setHTTPMethod:#"POST"];
//set request length
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//set request content type we MUST set this value.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//set post data of request
[request setHTTPBody:postData];
NSLog(#"%#", [request allHTTPHeaderFields]);
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//start the connection
[connection start];
return YES;
}
This string is not correct NSString *post = #"username=example1%40example.com&example2";
After ampersand you have to provide key=value.
#"key1=value1&key2=value2";
Example of working code:
In .h file set delegate:
#interface Controller <NSURLConnectionDataDelegate>
In .m file:
- (void)login {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeOut];
request.HTTPMethod = #"POST";
NSString *params = #"key1=value1&key2=value2";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
_data = [NSMutableData data];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Parse your '_data' here.
}

Iphone-SBJson returns null responseData for the connection which get late response in multiple request sending

Here, I tried to send Asynchronous call to python server using SBJson framework. For continuous multiple call with same request, gives null value in response string.
here, what I tried :
- (NSURLConnection *) GetHttpConnection:(NSString *)Path:(NSDictionary *)requestData:(UIView *)appView {
NSString *jsonReq = nil;
NSData *reqData = nil;
if (requestData != nil) {
jsonReq = [requestData JSONRepresentation];
reqData=[NSData dataWithBytes:[jsonReq UTF8String] length:[jsonReq length]];
}
NSString *urlString = [NSString stringWithFormat:#"%#/%#", URL, Path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
if (reqData) {
[request setHTTPBody:reqData];
}
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData data] retain];
}
return connection;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Connection Finish Loading >>>>> %#",responseString);
responseData = nil;
if (responseString && [responseString JSONValue] != nil) {
// process response string and send response back to delegate method
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData*)data {
[responseData appendData:data];
}
After tracing NSlog responses, I found this,
If I send same request 3 times (by pressing Update detail button)
connectionDidFinishLoading should call 3 times and it is calling it. but for any (one) request the respective response data returns null. Thats why the JSON stated below
JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x909d4b0 {NSLocalizedDescription=Unexpected
end of string}"
How can I overcome from this scenario? or Is there anything wrong in the code?
Thanks!
Your class is not re-entrant as there's only one reference to responseData. If two requests run at the same time Bad Things Will Happen. For this to work you'll need to either put your requestData in a dictionary keyed by the NSURLConnection, or create another instance of your downloader for each request.

Sending JSON Request to server?

I have following JSON for sending request on server
{
"name":"Home",
"latitude":"45.5037078163837",
"longitude":"-122.622699737549",
"radius":"240"
}
and URL of for request is
URL: https://api.geoloqi.com/1/place/create
I am making request like this,
NSString *urlString= #"https://api.geoloqi.com/1/place/create ";
NSURL* url = [[NSURL alloc] initWithString:urlString];
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\,\"radius\":\"500\ }";
jsonRequest = [self JSONString:jsonRequest];
NSData* requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [requestData length]];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
[url release];
[requestData release];
[requestDataLengthString release];
NSURLConnection *m_URLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
What is wrong with this request ?
Your JSON string seems to be missing 2 quotes after the longitude and radius values:
Change
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\,\"radius\":\"500\ }";
To this
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\",\"radius\":\"500\" }";
It is not clear from your question what is your issue with that.
Anyway, are you doing also:
[m_URLConnection start];
after creating the connection?
Alternatively, you could create the connection using
[– initWithRequest:delegate:startImmediately:][1]
which allows you to specify that the loading of data shall start immediately.
Also consider using [+sendAsynchronousRequest:queue:completionHandler:][2] as a convenience constructor for your connection.
The Webservice URL you are trying to hit is seem to be using SSL. You may need to put access token in request header in order to get the proper response from web service.
Please see the link for authentication:
https://developers.geoloqi.com/api/authentication

How to post a parameters to server api using HTTP POST method in iphone

i have application in which i have a web server api .this is my api
http://192.168.0.68:91/JourneyMapperAPI?RequestType=[<EntityKey>]&Command=[GET|SET|NEW]&Token=[token]&param...n=value..n
RequestType in the query string expects an entity name requested which could be any of the database tables.
Command, in the query string should specify the operation which needs to be performed on the specified request type which could be GET SET or NEW or any other entity specific command.
For eg. i have a register form which allows the user to register.
RequestType for register form is register so the api request on the submit button click of register form would be
http://192.168.0.68:91/JourneyMapperAPI?RequestType=Register&Command=NEW&firstname=rocky&lastname=singh&Username=rocky14&Password=[password]&Email=[email];
How to post this request to server api using http post method with all these parameters and values in it so that the values will be saved in the sever table named register .Please help me in solving this problem.thanks
You can use the below function for posting data to web-server.
-(void)callCommentWebService:(NSString *)pstrCommentXML{
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<getImageComment xmlns=\"http://tempuri.org/\">"
"<Commentsxml>%#</Commentsxml>"
"</getImageComment>"
"</soap:Body>"
"</soap:Envelope>", pstrCommentXML
];
//Create URL Request
NSURL *url = [NSURL URLWithString: #"http://www.website.com/website/WebService.asmx?op=getImageComment"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//Populate Headers
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [[NSMutableData data] retain];
}
}
Here,
url = you server web-service path
pstrCommentXML = you XML file whose format defined for upload
Then you can use simple delegate methods for getting response from server.
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response
{
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data
{
[webData appendData:data];
}
- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
}
Hope you got the point.
The easiest way IMHO would be to uses ASIHTTPRequest, or it subclass ASIFormDataRequest.
This let you easily upload text and data via POST as if it would be filling a web form — hence it name.

"Operation couldn't be completed. Connection reset by peer." with NSURLConnection on iOS

I'm struggling sending POST data to a server and receiving the correct response. I started by using setHTTPBody but moved to setHTTPBodyStream when I wasn't getting the correct server response for certain POST data and I read setHTTPBody has a memory leak on earlier iOS versions. The problem is setHTTPBodyStream causes the error - "Operation couldn't be completed. Connection reset by peer".
Here's the code:
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"secret but correct url goes here"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
[request setHTTPMethod: #"POST"];
[request setHTTPBodyStream: [NSInputStream inputStreamWithData: [[NSString stringWithFormat:#"username=%#&password=%#&score=%i",[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)ogl_view->username, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)text_field.text, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],ogl_view->score[0]] dataUsingEncoding:NSUnicodeStringEncoding]]];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest: request delegate:self];
if (connection){
received_data = [[NSMutableData data] retain];
ogl_view->section = CURLING_PROCESS_CREDENTIALS;
}else{
ogl_view->section = CURLING_LOGIN_OR_REGISTER;
UIAlertView *connection_alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"Can't connect to server" delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[connection_alert show];
[connection_alert release];
}
I can verify the server is fine and it works when I try a web-browser.
Can somebody get me on the right track to sending data with HTTP and the POST method correctly?
Thank you for any help.
Try using this (with your own values):
NSString* post = #"username=myUser&password=myPass&score=20"; //customize this
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:#"http://my.request.com"]; //customize this
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:timeout];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
You'll then need to implement the NSURLConnectionDelegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)remoteData;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
In the end, remember to release the NSURLConnection.
Edit: Didn't see that you wrote that setHTTPBody leaks... never seen that happening. Anyway, here is some code that should work...