Sending Post http request from nsstring - ios

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.

Related

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 send data in url to server?

http://novatoresols.com/demos/blow/users/add.json?json={"email":"ali"}
How can I send a key and data to web? Here "email" is the key and "ali" is the value in URL.
Code:
NSURL *url=[NSURL URLWithString:[hostURL stringByAppendingFormat:#"users/add.json?json="]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString * params =#"{\"email\":\"Ali\"}";
[request setHTTPMethod:#"POST"];
// This is how we set header fields
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Simply Try with this :
NSString * params =#"{\"email\":\"Ali\"}";
NSURL *url=[NSURL URLWithString:[hostURL stringByAppendingFormat:#"users/add.json?json=%#",params]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog (#"%#",data);

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

NSURLConnection with POST doesn't work

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");
}

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