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];
Related
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.
I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[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];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method
I got the following Postman request which works fine (Screenshot http://postimg.org/image/s7zm3qhvh/). But when i try the same in iOS it will not work. Maybe someone can give me some information why.
My Objective-c Code:
UIImage *yourImage= [UIImage imageNamed:#"login-main-bg.png"];
NSString *imageString = [UIImagePNGRepresentation(yourImage) base64Encoding];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
imageString, #"image",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(#"%#",[error localizedDescription]);
}
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://server.website.net/api/collaboration/ImageTest"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
//print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
I hope someone can help me! Thank you!
You're posting a json representation of a base64 encoded string of your image. The postman request is doing a raw binary post with multipart form boundaries.
You want something more like what is shown here https://stackoverflow.com/a/23517227/96683
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];
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");
}