POST to server results in GET request - objective-c

I'm trying to do a simple POST request to a server, with this code:
NSString *post = [[NSString alloc] initWithFormat:#"email=%#&password=%#", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:#"http://eng.studev.groept.be/web2.0/a11_web02/testApp.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postEncoded];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
When debugging on the server, this actually results in a GET request. That explains why I'm getting a PHP error when trying to read $_POST[ ] variables. Bottom line: why isn't the setHTTPMethod: being accepted?
(extra information: when just coding in PHP on the server, use of POST works normally)

Related

Checking data sent in http post Request

Is it possible to check the data which I have sent in HTTP POST request, by logging the request in XCode.
Here is my code:
NSString *post = [NSString stringWithFormat:#"Firstname=%#&Lastname=%#&Email=%#",firstName,lastName,emailId];
NSLog(#"%#", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.abcde.com/xyz/login.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
**NSLog(#"%#", request );**
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I am logging the request as shown above in Bold. But here I am able to see only my Url and not any post data.
If it is not possible to see data here where can I see the data sent in http request.
If you want just check what data are you sending then I suggest you to use this awesome tool http://www.charlesproxy.com. It's very simple and powerful.
Just run Charles and do your request via simulator.

Objective C webservice request works with http:// but not https://

Any suggestions? The code works perfectly with http but not https://. I wonder if it's the port. The certificate is valid. I get a "server pretending to be another server" error.
NSString *post=[[NSString alloc] initWithFormat:#"strEmail=%#&strPassword=%#", [self.txtUsername text], [self.txtPassword text]];
NSLog(#"PostData%#", post);
// NSURL *url= [NSURL URLWithString:#"http://dipinkrishna.com/jsonlogin.php"]; // does work
NSURL *url= [NSURL URLWithString:#"https://dev.myrdcm.com/felipe.asmx?op=GetSignIn”];// does not work
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-fore-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",request);
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse * response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
If you get a "server pretending to be another server" error, then certificate is not valid. I have opened yours url in browser and see that certificate is expired.

post request to server does not send the content of textfields?

I'm trying to send the content of my textfields firstname and lastname with my button sendpost to my php server. Once I run my app and fill my textfields with some random text and press send, I receive an e-mail on my server but there is no content.
(void) sendAction{
NSError *error = nil;
NSString *postparams = [NSString stringWithFormat:#"info=%#_%#",firstname.text,lastname.text];
NSData * postdata = [postparams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postlength= [NSString stringWithFormat:#"%d",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://faketest.com/test/mail.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postdata];
NSData * rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *rawdatastring =[[NSString alloc]initWithData:rawdata encoding:NSUTF8StringEncoding];
NSLog(#"%#",rawdatastring);
}
I believe it may be because you're using a "Current-Type" header, instead of the usual "Content-Type" header. Try the following and see if it solves the problem:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];

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
}

Post data in Objective C using Json

I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];