How to send login and password to a server using ASIHTTPRequest? - iphone

I'm pretty new to everything that deals with http and stuff like that and i know almost nothing about how http methods work so i need your advice. In my app i have to send login and password to a server and get a response. By now i'm trying to write a method (it's called STUB in English i believe) which will work in a general way without communicating to actual server. Should i use POST method in a manner similar to:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:some_server_url];
[request addPostValue:passwordString forKey:loginString];
or something else? if first how do i receive the response from the server? Could you please show me few lines of code?

You can pass login details to server using HTTP POST method like this :
-(NSDictionary*)userLogIn:(NSMutableDictionary*)inputDictionary{
SBJSON *parser = [[SBJSON alloc] init];
NSString *convertedString=[NSString stringWithFormat:#"login=%#&password=%#",username, password];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"Give the url here"]];
[request setHTTPBody:[convertedString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"XXXX" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"POST"];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
[parser release];
[json_string release];
return statuses;
}
This is a sample code and you have to change according to your requirements.

Related

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

How to post multiple data to web server

I have below code for posting data to the web server but it gives me null response, I have multiple data and they are:-
date,
rig,
driller,
offsider-1,
offsider-2,
shift
,
project,
supervisoremail,
geologistemail,
comments,
plants[0][name-id],
plants[0][start-usage],
plants[0][end-usage],
consumables[0][category],
consumables[0][name-id],
consumables[0][used],
consumables[0][code],
consumables[0][description],
I have to post this data and I used this code for posting but it didn't work for me. Please help me out.
NSURL *url=[NSURL URLWithString:#"http://www.mydor.com.au/staff/dor/idorInsert"];
NSString *post =[[NSString alloc]initWithFormat:#"date=15/08/2012&rig=53&driller=207&offsider-1=131&offsider- 2=236&shift=day&project=24&supervisoremail=24&geologistemail=24&comments=&plants[0][name- id]=286&plants[0][start-usage]=1.0&plants[0][end-usage]=0.0"];
NSLog(post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"here u re");
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"here also called");
NSLog(#"%#",data)
Thanks in advance.
Here is an article which demonstrates how to consume .NET Web service using iOS application. You can use the techniques discussed in the article:
http://www.highoncoding.com/Articles/809_Consuming__NET_Web_Services_in_an_iOS_Application.aspx
Almost all the work I do involves .NET with iOS. Have a look here for the network class I wrote and use all the time (AFNetworking based). I prefer to use a regular aspx form instead of an asmx web-service. I do this because I don't want to expose any web-methods to snooping visitors and I use an API key check before returning anything in the aspx form. I can send you an example .NET code (written in VB.NET) if you need me to.

Issue in Image uploading - base64 encoding

I am passing base64 encoded image string to the server side with the HTTP PUT method.I have tried several times but getting error message as response. That error message is because null value is getting in the server side. I have checked the same, in android code and its working fine there. I am attaching my code below.
SBJSON *parser = [[SBJSON alloc] init];
NSString *url=[NSString stringWithFormat:#"The URL i am using"] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"XXXXX" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"PUT"];
NSString *input=[NSString stringWithFormat:#"abc[image]=%#",base64encodedString];
[request setHTTPBody:[input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
[parser release];
[json_string release];
return statuses;
I am getting error message from the server side like this: "xxxxxx.jpg is not recognized by the 'identify' command."
Kindly suggest a solution.
At last i found that the content type should be changed to "multipart/form-data" from "application/x-www-form-urlencoded". Can anyone please tell me how pass Base encoded string using this way? Pls...i am behind this issue for the last 20 days...
There could be a difference in the Base64 routine. Base64 encode the same data on the server and the iPhone and compare.
Using the simulator use a network snooper such as Wireshark on the Mac to see what is really going out and the full return from the server. If you are using SSL you can use the Mac app Charles to see the data.

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 send the updated data using json to server in iphone?

am using web services (JSON). from json am getting data this data loading into tableview am trying to edit this data but after edit the data how to send this updated data to server.
please any one help me?
try this will help you.. this is the post method for updating data in WS .
NSString *post =[NSString stringWithFormat:#"uid=%#&firstname=%#&lastname=%#&phone=%#&bday=%#&about_me=%#&image=%#&image_code=%#&contact_number=%#",LoginID,fname,lname,cn,bday,abtme,strimage11,c11,cn];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"YOUR LINK"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *uData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:uData encoding:NSUTF8StringEncoding];
//
NSMutableDictionary *temp = [data JSONValue];
//
NSLog(#"%#",temp);
I am assuming you have your edited data, then
Form your json. There are several libraries out there which can help you.
Know the hostname of your server.
Know which API to hit on your server.
then pass this json as POST (GET is also ok, but POST is preferred).
Process this received json on your server.
Hope this helps. Nothing much to it actually.