Why is API rejecting my JSON? - ios

I can add an object to an API via JSON when I send the request using byte char[] however it doesn't work when I convert an NSDictionary to NSData and send that. What's the problem here ?
Here's when it works.
// Request
NSURL* URL = [NSURL URLWithString:#"SOME URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
// Headers
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Body
const char bytes[98] = "{\n\t\"user\" :\n\t{\n\t\t\"email\" : \"test#gmail.com\",\n\t\t\"username\" : \"example\",\n\t\t\"password\" : \"cryptx\"\n\t}\n}";
request.HTTPBody = [NSData dataWithBytes:bytes length:98];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
This is when it doesn't work:
- (void)addUser:(User *)user
{
NSURL* URL = [NSURL URLWithString:#"API_URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *data = [self createJSONWithUsername:#"X" andEmail:#"x#X.com" andPassword:#"pass"];
[request setHTTPBody:data];
NSLog(#"%#", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
- (NSData *)createJSONWithUsername:(NSString *)username andEmail:(NSString *)email andPassword:(NSString *)password
{
NSArray *objects = [NSArray arrayWithObjects:password, email, username, nil];
NSArray *keys = [NSArray arrayWithObjects:#"password", #"email", #"username", nil];
NSDictionary *userDataDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *userDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userDataDictionary, #"user", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error:nil];
return jsonData;
}
The second one does not add the user while the second one does.
EDIT
JSON BEING SENT i.e. the jsonString variable
{
"user" : {
"email" : "x#X.com",
"username" : "X",
"password" : "pass"
}
}

This is how I'd do it. It's pretty much exactly what I use in a few apps. I formatted around your provided code...
- (void)addUser:(NSDictionary *)sentuserdetails {
NSURL *url = [NSURL URLWithString:#"SOME URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sentuserdetails options:NSJSONWritingPrettyPrinted error:nil]; //don't set error to nil, handle the error
[request setHTTPBody:jsonData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}

Related

PayPal error 580001 HTTP Request from iOS

Having some difficulties in implementing Adaptive payments in iOS and unfortunately there is very little documentation on PayPal's website or response. This is the code:
- (void)makePaymentSandbox{
NSError *error;
//NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
//setting
[request setHTTPMethod:#"POST"];
//headers
[request addValue:#"alex-facilitator_api1.fastwebnet.it" forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
[request addValue:#"FW79EZXASW69NE8X" forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[request addValue:#"ABZua9nnv9oieyN4MwVt15YdgetaJHcyzqOHjkLbuM-bGRoI7WRS" forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
//NV
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[request addValue:#"APP-80W288712P519543T" forHTTPHeaderField:#"X-PAYPAL-APPLICATION-ID"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"en_US" forHTTPHeaderField:#"Accept-Language"];
//data
/*NSString *userUpdate =[NSString stringWithFormat:#"clientDetails.applicationId=%#&actionType=%#",#"APP-80W284485P519543T", #"PAY",nil];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
[request setValue: [NSString stringWithFormat:#"%lu", (unsigned long)[data1 length]] forHTTPHeaderField:#"Content-Length"];*/
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:
#"PAY", #"actionType",
#"USD", #"currencyCode",
#"http:\\www.cleverlyapp.com", #"cancelUrl",
#"http:\\www.cleverlyapp.com", #"returnUrl",
#"ReturnAll", #"requestEnvelope.detailLevel",
#"en_US", #"requestEnvelope.errorLanguage",
#"seneder#email.com", #"senderEmail",
#"0.1", #"receiverList.receiver(0).amount",
#"a-buyer#fastwebnet.it", #"receiverList.receiver(0).email",
#"0.1", #"receiverList.receiver(1).amount",
#"a-facilitator#fastwebnet.it", #"receiverList.receiver(1).email",
#"APP-80W284485P519543T", #"clientDetails.applicationId",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
Here's the response:
String: {
error = (
{
category = Application;
domain = PLATFORM;
errorId = 580001;
message = "Invalid request: {0}";
severity = Error;
subdomain = Application;
}
);
responseEnvelope = {
ack = Failure;
build = 17325060;
correlationId = e82ede718b929;
timestamp = "2015-07-14T09:50:06.222-07:00";
};
}
check these please:
Adaptive Payments Pay API Error 580001
580001 Invalid request: {0} PayPal (PHP)
Error 580001
some have to do with encoding, set as JSON, but actualy sent as URL-encoded, etc, others have to do with currency and currency format used (e.g values sent should not include currency sign etc..)
Finally got it to work. The headers are correct, the input data had some problems. This is the correct version of the code:
- (void)makePaymentSandboxWithPreapprovalToEmail:(NSString *)toEmail withCurrency:(NSString *)currency andAmount:(NSString *)moneyAmount completition:(void (^)(BOOL, NSString *))block{
NSError *error;
NSURL *url = [NSURL URLWithString:#"https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
//setting
[request setHTTPMethod:#"POST"];
//headers
[request addValue:#"alex.rietmann-facilitator_api1.fastwebnet.it" forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
[request addValue:#"FW7ADTYZFP68XE0X" forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[request addValue:#"ABSua9nnv9nnkoN4MwVt15YdgetaJHcyzqOHjkLbuM-bGRoI7JRS" forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
//NV
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[request addValue:#"APP-80W284485P519543T" forHTTPHeaderField:#"X-PAYPAL-APPLICATION-ID"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"en_US" forHTTPHeaderField:#"Accept-Language"];
//other email
NSDictionary *receiver0 = [[NSDictionary alloc] initWithObjectsAndKeys: toEmail, #"email", moneyAmount, #"amount", #"true", #"primary", nil];
//my account
NSDictionary *receiver1 = [[NSDictionary alloc] initWithObjectsAndKeys: #"alex.rietmann-facilitator#fastwebnet.it", #"email", #"2", #"amount", nil];
NSDictionary *options0 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSArray arrayWithObjects:receiver0, receiver1, nil], #"receiver", nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:
#"PAY", #"actionType",
#"EACHRECEIVER", #"feesPayer",
#"true", #"reverseAllParallelPaymentsOnError",
currency, #"currencyCode",
[PaymentManager readPaymentCode], #"preapprovalKey",
[PaymentManager readPaymentEmail], #"senderEmail",
#"http:\\www.apple.com", #"cancelUrl",
#"http:\\www.google.com", #"returnUrl",
[[NSDictionary alloc] initWithObjectsAndKeys:#"en_US", #"errorLanguage", #"detailLevel", #"ReturnAll", nil], #"requestEnvelope",
//[[NSDictionary alloc] initWithObjectsAndKeys: options0, #"0", nil], #"receiverList",
options0, #"receiverList",
[[NSDictionary alloc] initWithObjectsAndKeys:#"APP-80W284485P519543T", #"applicationId", [self getIPAddress], #"ipAddress", nil], #"clientDetails",
//#"APP-80W284485P519543T", #"clientDetails.applicationId",
//[self getIPAddress], #"clientDetails.ipAddress",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
MyConnection * connection = [[MyConnection alloc]initWithRequest:request];
[connection setCompletitionBlock:^(id obj, NSError *err) {
if (!err) {
NSError *error = nil;
NSDictionary* revDicn =[NSDictionary dictionary];
revDicn = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Response: %#", revDicn);
if ([[revDicn objectForKey:#"paymentExecStatus"] isEqualToString:#"COMPLETED"]) {
block(YES, [revDicn objectForKey:#"payKey"]);
}else{
block(NO, #"");
}
} else {
//There was an error
block(NO, #"");
}
}];
[connection start];
}
This line is optional:
[PaymentManager readPaymentCode], #"preapprovalKey",
The use of it depends on whether you wish to use pre-approval or not. This explains in detail the use of pre-approval: https://developer.paypal.com/webapps/developer/docs/classic/adaptive-payments/ht_ap-basicPreapproval-curl-etc/. Replace the input values in the code above and you will get the pre-approval key.
Working code. Please check.
int amount = 195;
// int x = 146;
NSDictionary *parameters;
parameters = #{
#"actionType" : #"PAY",
#"currencyCode" : #"USD",
#"receiverList" : #{#"receiver" : #[#{#"amount": [NSNumber numberWithInt:amount],#"email":#"testerigniva12#gmail.com"}]},
#"returnUrl" : #"https://example.com/return",
#"cancelUrl" : #"https://example.com/cancel",
#"requestEnvelope" : #{#"errorLanguage":#"en_US", #"detailLevel":#"ReturnAll"}
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSURL *url = [NSURL URLWithString:#"https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
//headers
[request addValue:#"testios1_api1.grr.la" forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
[request addValue:#"TP3DRR4WLYAJ5HWR" forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[request addValue:#"AKiJVI-zRf1GGbfcTE2iPRb31l2ZAdq7HY4WrG6uxNAhc79Vtg7myGk3" forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
//NV
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[request addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[request addValue:#"APP-80W284485P519543T" forHTTPHeaderField:#"X-PAYPAL-APPLICATION-ID"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"en_US" forHTTPHeaderField:#"Accept-Language"];
[request setHTTPBody:jsonData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// do something with the data
NSDictionary* revDicn =[NSDictionary dictionary];
revDicn = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Response: %#", revDicn);
}];
[dataTask resume];

How to send an object as a parameter for a POST request in iOS?

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

how to pass a dictionary using NSURLSession in post method?

I do not know how to pass values in dictionary into server using NSURLSession via POST. Please help me to solve this problem.
My dictionary contains contact information (name and phone number only), where the key is the person's name and the value is their phone number.
I have sample code using nsurl connection - how can I convert it to use NSURLSession?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://holla.com/login"]];
request.HTTPMethod = #"POST"; [request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I solve the problem by using the following method:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:#"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[postDataTask resume];

IOS Json error in sending to http post and setting entity

Hi I am sending an http post request to a server the java code i am referring to has a method as set entity in the post request. How can i achieve this in iOS .
I am presently putting the json data to be sent in the body but am getting the error
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
but was
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
my code is
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,#"text",#"Sent",#"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,#"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Add this in your code:- [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

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