NSURLConnection with POST doesn't work - ios

I'm trying request a URL parsing parameters with POST, but mypage.php is not receiving this parameters...
Here is my code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://myurl/mypage.php"]];
NSString *params = [[NSString alloc]initWithFormat:#"name=%#&surname=%#&location=%#&email=%#&password=%#&gender=%#&tipo=%#", name, surname, location, email, password, gender, tipo];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(params);
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
else
{
}
and mypage.php
if($_POST['name'] != "" && $_POST['email'] != "")
//Here the $_POST['name'] and the $_POST['email'] are empty...

You're not starting the connection. You should do it with a [conn start];

Try this:
NSString *params=[NSString stringWithFormat:#"name=%#&surname=%#&location=%#&email=%#&password=%#&gender=%#&tipo=%#", name, surname, location, email, password, gender, tipo];
NSData *postData=[params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://myurl/mypage.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:#"%i",postData.length] forHTTPHeaderField:#"Content-Length"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data!=nil) {
NSString *output=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"output: %#", output);
}else{
NSLog(#"data is empty");
}

Related

Sending an HTTP POST with header form-data request on iOS

I am calling odata post api having HTTP header filed is "form-data". Below is my code :-
NSURL *restURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:restURL];
[request setHTTPMethod: getorpost];
if (jsonData != nil) {
[request setValue:#"application/form-data" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
}
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData alloc] init];
}
And i am getting below response:-
Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details
But, it is working fine in Postman. Can anyone please suggest where is the fault in my code.
Thanks,
Use this
NSURL *url = [NSURL URLWithString:url_str];
NSLog(#"%#",datastring);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[datastring dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestBody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestBody];
httpResponse=[[NSHTTPURLResponse alloc]init];
receivedData=[[NSMutableData alloc]init];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"%# calling with datastring: %#", url, datastring);
}
delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%d", httpResponse.statusCode);
NSLog(#"%#",[httpResponse description]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
receivedData = [[NSMutableData alloc]init];
httpResponse=[[NSHTTPURLResponse alloc]init];
NSLog(#"%#",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSString *retVal = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"retVal=%#",retVal);
}
-(void)ViewDidLoad
{
NSMutableDictionary *postData = [[NSMutableDictionary alloc]init];
[postData setObject:uid forKey:#"id"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"%#",jsonInputString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"YOUR URL "]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[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];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *jsonDict;
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonDoct == %#",jsonDict);
}
else
{
NSLog(#"RESONPSE IS NULL");
}
if (error)
{
NSLog(#"error %#",error.description);
}
}

Sending Post http request from nsstring

I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

unsupported URL error code -1002

Hi Please help me how to prepare NSMutableURLRequest for below api
URL : www.XXXXXXXX.com/api.php
For Login :-
www.XXXXXXXXXXXX.com/api.php?task=login
POST Data :-
"email" => User's email
"pw" => User's Password
json response: session id on successful login
Am trying like this.
NSMutableURLRequest *request;
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.XXXXXXXX.com/api.php?task=login"]];
[request setHTTPMethod:#"POST"];
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
One reason could be that you forgot to add the "http:" scheme:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.XXXXXXXX.com/api.php?task=login]];
HERE --^
Note also that the correct way to set body data and in particular the length is
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:postData];
because the length of the UTF-8 encoded data can be different from the (Unicode) string length.
I ran into this error when I specified my base URL with a variable that accidentally contained a new line.
Try this:
NSError *error;
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithUTF8String:[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
}
[connection start];

How to submit text messages to server via ios apps

my problem is I cannot send the text messages to server. Im using asihttprequest. I have define the USERNAME, UUID, PASSWORD, API_PASSWORD and NUMBER myself. What I want to do is just send the data to the server url given. Here is my code:
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"https://cc.frifon.net_dosmssend/"]];
[request setDelegate:self];
[request setNumberOfTimesToRetryOnTimeout:3];
[request setRequestMethod:#"POST"];
[request setPostValue:USERNAME forKey:#"sip"];
[request setPostValue:PASSWORD forKey:#"pwd"];
[request setPostValue:UUID forKey:#"uuid"];
[request setPostValue:API_PASSWORD forKey:#"key"];
[request setPostValue:messageText forKey:#"message"];
[request setPostValue:NUMBER forKey:#"to"];
[request setPostValue:#"Submit" forKey:#"submit"];
[request start];
nil;
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
messageText.text = response;
}
}
Try this,
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
NSString *serviceString = https://cc.frifon.net_dosmssend/;
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[serviceString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
[request setDelegate:self];
request.requestMethod = #"POST";
request.timeOutSeconds = 30.0;
[request addPostValue:USERNAME forKey:#"sip"];
[request addPostValue:PASSWORD forKey:#"pwd"];
[request addPostValue:UUID forKey:#"uuid"];
[request addPostValue:API_PASSWORD forKey:#"key"];
[request addPostValue:messageText forKey:#"message"];
[request addPostValue:NUMBER forKey:#"to"];
[request addPostValue:#"Submit" forKey:#"submit"];
[request startAsynchronous];
}
- (IBAction)sendClicked:(id)sender {
// Add you all data in below dictionary
NSDictionary *dictionary = #{#"action":#"login",#"nick_name":nikname,#"password":pass};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *jason =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON summary: %#", jason);
NSString *address = [NSString stringWithFormat:#"%#",#"www.demo.com"];
address= [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:data];
responseData = [[NSMutableData alloc] init];
NSURLConnection *Conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[Conn start];
}

send JSON Object Request to Server

Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Resources