objective-c HTTP POST send request as form - ios

I have used POST method to call API with header values and params for body on my application.
The server only accepts forms in the format
"form": {
"action" : "login",
"user" : "311"
},
When we use code
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSString *params = [self makeParamtersString:parameters withEncoding:NSUTF8StringEncoding];
NSData *jsonData2 = [params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
My form looks like this
form = {
action = login;
user = 311;
};
Can you produce the result you want?
Could you please help me to solve this issue.

Try
NSString *urlString = [NSString stringWithFormat:#"%#", url_string];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSDictionary *parameters = #{#"action": #"login", #"user": #"311"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: parameters options:0 error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

How about change the parameters like this.
NSDictionary *parameters = #{#"form":#{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

Try This if you need base64 encoding
NSMutableDictionary *param = [#{#"form":#{#"action": #"login", #"user": #"311"}} mutableCopy];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:serviceURL];
NSString *strEncoded = [self encodeParameters:param];
NSData *requestData = [strEncoded dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestData];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)requestData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Function encodeParameters
+(NSString *)encodeParameters:(NSDictionary *)dictEncode
{
// Encode character set as per BASE64
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"/+=\n"] invertedSet];
NSMutableString *stringEncode = [[NSMutableString alloc] init];
NSArray *allKeys = [dictEncode allKeys];
for (int i = 0;i < allKeys.count; i++) {
NSString *key = [allKeys objectAtIndex:i];
if([dictEncode valueForKey:key])
{
[stringEncode appendFormat:#"%#=%#",key,[[dictEncode valueForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:URLBase64CharacterSet]];
}
if([allKeys count] > i+1)
{
[stringEncode appendString:#"&"];
}
}
return stringEncode;
}

Try this
NSURL * url = [NSURL URLWithString:#"%#",url_string];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession * session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSDictionary * paramters = [NSDictionary dictionaryWithObjectsAndKeys:#"login",#"action",#"311",#"user", nil]; // [NSDictionary dictionaryWithObjectsAndKeys:#"value",#"key", nil];
NSDictionary *params = #{#"form": paramters};
NSError *err = nil;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];

Try this,
NSString *parameters = #"\"form\":{\"action\" : \"login\", \"user\" : \"311\"}";
NSData *jsonData2 = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData2];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];

NSError *error;
NSDictionary *parameters = #{#"form": #{#"action": #"login", #"user": #"311"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted error:&error];
request.HTTPBody = jsonData
//Using NSURLSession is better option than using NSURLConnection
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary* respondData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#", respondData);
} else{
NSLog(#"%#", error);
}
}];
[dataTask resume];

Try AFNetwoking
NSString *urlString = [NSString stringWithFormat:#"URL"];
NSDictionary *para= #{#"action": #"login", #"user": #"311"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Related

How to POST { "username"="usernameValue" "password"="passsworValue" } as json body in objective c

I tried Like this..
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"username=%#&pasword=%#",self.TextUsername.text,self.TextPassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}
Using AFNetworking:
-(void)Gettok {
NSString* URLString = [NSString stringWithFormat:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:self.TextUsername.text forKey:#"username"];
[params setObject:self.TextPassword.text forKey:#"password"];
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError * error;
NSArray *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
NSLog(#"--------------------respons : %#--------------------",result);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"----------------------Error ; %#------------------------------",error);
}];
}
The content type of the request body. Set this value "Content-Type:application/json"
In response i get decode error message.I already got the get JSON getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
In the first NSURLSession style you don't send json to the service. Try it like this:
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *dict = #{#"username":self.TextUsername.text,
#"password":self.TextPassword.text};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}

Json Code is not working

NSString *urlString = #"http://chkdin.com/dev/api/peoplearoundmexy/?";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *parameterString=[NSString stringWithFormat:#"skey=%#&user_id=%#",#"XXXXXXX",#"3225"];
NSLog(#"%#",parameterString);
[request setHTTPMethod:#"POST"];
[request setURL:url];
[request setValue:parameterString forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);
This is my json parsing, my problem is when I am hit this api it is showing
{
message = "Valid skey required.";
status = 0;
}
But this api is working in safari.i am think is the problem is for request adding to url wrong. can you help me please....
i got response through AFNetworking 3
try this
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://chkdin.com/dev/api/peoplearoundmexy/?" parameters:#{#"skey":#"sa6rw9er7twefc9a7dvcxcheckedin",#"user_id":#"3225"} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
}];
i tried following code without AFNetworking and its working fine.
NSString *post = [NSString stringWithFormat:#"skey=%#&user_id=%#",#"sa6rw9er7twefc9a7dvcxcheckedin",#"3225"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://chkdin.com/dev/api/peoplearoundmexy/?%#",post]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:nil];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSLog(#"%#",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dict);

How to request datas to server in post method ios?

Hi I am new to ios post method.In my app i want to show list of values.
The request format is:
{"customerId":"000536","requestHeader":{"userId":"000536"}}
The code i used is:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
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/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error){
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}
];
The response is : (null)
How to request the values with same format as shown above?Thanks in advance.
Use This Code
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
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/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err)
{
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}];
[task resume];

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];

Format for POST Request in iOS

I am able to get the JSON Response in iOS code through POST Request only when the parameters are empty. Response from Server is { Token = "" }
NSString *postData = [NSString stringWithFormat:#""];
But when I add any parameters like shown below, I get 400 status code as response.
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
The interesting thing is the same parameters work in REST Client perfectly and gets a response. And also works in Android code too. In android a JSON object is created then these key value pairs are added to the JSON object
JSONObject jsonObj = new JSONObject();
jsonObj.put("userName", "apple#test.com");
jsonObj.put("deviceCode", "Dev455");
jsonObj.put("pwd", "225");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httppost.setEntity(entity);
and request and then receives the correct response.
Can anyone suggest me the equivalent code for iOS for the above Android code?
My present code is
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSString *postData = [NSString stringWithFormat:#"userName=aps#test.com&deviceCode=bhj234&pwd=1234"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSLog(#"post:%#",postData);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSLog(#"post:%#",[postData dataUsingEncoding:NSUTF8StringEncoding]);
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
User AFNetworking and improt the following in your class
#import "AFNetworking.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPRequestOperation.h"
Use the following code to for Post request:
- (void)sendPOSTRequest {
NSArray *keys = [NSArray arrayWithObjects:#"userName",#"deviceCode",#"pwd",nil];
NSArray *objects = [NSArray arrayWithObjects:#"apple#test.com",#"Dev455",#"225", nil];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[manager POST:#"yourURL" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:[operation responseData] options:0 error:&error];
NSLog(#"JSON: %#", json);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
In case if everything else doesn't work, try to pass parameters in url:
NSString *URL=[[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv.svc/Login?userName=aps#test.com&deviceCode=bhj234&pwd=1234"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSLog(#"post:%#",URL);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Once it worked for me, however this of course doesn't answer what is the problem with your code.
I found the answer for my question.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"aps#test.com" forKey:#"userName"];
[dict setValue:#"vikkj107" forKey:#"deviceCode"];
[dict setValue:#"1234" forKey:#"pwd"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONReadingMutableLeaves error:nil];
NSMutableString *URL=[[NSMutableString alloc] initWithString:#"http://***.***.**.***/Serv/Register"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *resultStr=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

Resources