Sending post variables to iOS form - iphone

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.
}

Related

Http Post Request With Parameters

I have a simple asp.net web service which returns json format data. I want to send http post request with parameter for getting json data. How can I send request and get data ?
post request:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
answer:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
I'm trying some codes but they didn't work.
NSString *firmadi =#"";
NSMutableData *response;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:#"800"];
response = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];
NSString *params = [[NSString alloc] initWithFormat:#"firID=%#",firid];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
response = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
[response setLength:0];
NSURLResponse * httpResponse;
httpResponse = (NSURLResponse *) responsed;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
//NSLog(#"webdata: %#", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(#"error with the connection");
[connection release];
[response release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
What are you doing here:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
This line returns a NSURLConnection but you are not storing it. This is doing nothing for you.
You are clearing your data before you read it:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
Edit
-(IBAction)buttonClick:(id)sender {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:15];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[#"firID=800" dataUsingEncoding:NSUTF8StringEncoding]];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
}
#pragma NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
I suffered this problem this morning and I just figure it out now. I guess the key to your question is How to use POST method with parameter. Actually, it is quite simple.
(1) First, you should make sure your file is ready to send. Here we say it is an NSString called stringReady. We use it as a parameter in our method called postRequest (Here is not the HTTP POST parameter we want to talk about. Don't worry).
// Send JSON to server
- (void) postRequest:(NSString *)stringReady{
// Create a new NSMutableURLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.xxxxxx.io/addcpd.php"]];
[req setHTTPMethod:#"POST"];
(2) Now, we say it the parameter that the server wants to get is called "data", this is the way how to insert your parameter to the HTTP body.
// Add the [data] parameter
NSString *bodyWithPara = [NSString stringWithFormat:#"data=%#",stringReady];
See, it's how you add a parameter when using POST method. You just simply put the parameter before the file that you want to send. If you aleary konw what your parameter then you may better to check this website:
https://www.hurl.it/
This will help you to test if you are sending files properly and it will show the response at the bottom of the website.
(3) Third, we pack our NSString to NSData and sent it to server.
// Convert the String to NSData
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Set the content length and http body
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[req addValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
// Create an NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something with response data here - convert to JSON, check if error exists, etc....
if (!data) {
NSLog(#"No data returned from the sever, error occured: %#", error);
return;
}
NSLog(#"got the NSData fine. here it is...\n%#\n", data);
NSLog(#"next step, deserialising");
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#"so, here's the responseDict\n\n\n%#\n\n\n", responseDict);
}];
[task resume];}
Hope this can help somebody who gets stuck at here.

How to login a server and get page source on objective-c?

I am trying to login a server by sending my username and password by POST method by NSURLConnection on objective-c but I get this from my NSLog
NSLog:
NSLog:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
What it writes to the console:
404 Not Found
Not Found
Sorry!The page requested was not found.
Why does this happens? Why do I get Not Found page instead of the index page? What do I do wrong? By the way I am trying to connect https not http I don't know does Here is the source code:
#interface ProjectViewController ()
#property NSURLConnection * urlConnection;
#property NSMutableData * responseData;
#end
#implementation ProjectViewController
#synthesize responseData =_responseData;
- (IBAction)LoginButton:(UIButton *)sender {
NSMutableURLRequest *request = nil;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://loginpage.com"]];
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];
//[self performSegueWithIdentifier:#"LoginComplete" sender:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//Oops! handle failure here
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
//NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields]; //This would give you all the header fields;
//NSLog(#"%#",headerFields);
}
}
#end
What I just recognized is if I put the part of POST request in to comment it prints the page source to the console but of course I can't send my username and password to the server. I just get the login page's source code but I want to get the source code after I login. Actually I want to redirect to another page by using this session.
This part:
NSString *post = [NSString stringWithFormat:#"sid=%#&PIN=%#", #"username", #"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
is the certificate used on the website self signed? did you try to make the request in a webview to see if it works there? not in an nsurlrequest?
try this response maybe it will give you some hints.

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

HTTP POST request to PHP server with the signup details encrypted as HTTP parameters

How to post HTTP POST request to PHP server with the signup details encrypted as HTTP parameters. Can you post me a sample code for my requirement?
You can use ASIHTTPRequest and you can it like this:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];
[request setRequestMethod:#"POST"];
[request setPostValue:#"..." forKey:#"user"];
[request setPostValue:#"..." forKey:#"password"];
[request setDelegate:self];
[request startAsyncrhonous];
There are delegate methods for request like request is finished or failed as
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Response %d ==> %#", request.responseStatusCode, [request responseString]);
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(#"Response %d ==> %#", request.responseStatusCode, [request responseString]);
}
You can always download the ASIHTTPRequest and can visit documentation too for any further help.
Hope this helps!
NSURL *url = [NSURL URLWithString:#"http://xyz"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSString *req;
req = [NSString stringWithFormat:#"Name=%#&Password=%#",userName,pass];// userName and pass are string
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [req dataUsingEncoding:NSISOLatin1StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
Below is a delegate which will bring data
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
NSError *erro;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&erro];
NSLog(#"your data in dictionary is = %#",jsonData);
}
hope this will help you !!!

get return result after post to server (from iphone)

I make iphone application, post parametes to JSP (test.jsp in server) from iphone. The following is my codes:
NSData *postData = [#"&test=123&field=456" dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Init and set fields of the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:#"http://mydomain.com/test.jsp"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// Return data of the request
NSData *receivedData = [[NSMutableData data] retain];
}
[request release];
But my problem is: I can not get return result from JSP server.
How I can setup in JSP to get return result in iPhone? and in iPhone too?
Thank all
Do you implement this in your delegate:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
Data won't just magically appear in your receivedData instance. You need to implement the delegate methods for NSURLConnection. Take a look at Apple's documentation on how to this all properly.