Error sending JSONArray parameter in url (iOS) - ios

i need to convert an array into json and send it as a parameter in a url along with other parameters. I am using jsonKit for json conversion and AFNetworking for network communication.But it always gives exception in the json at the server.
Here is the code used for son conversion:
NSString *jsonData = [self.finalArray JSONString];
NSString *data = [NSString stringWithFormat:#"%s",[jsonData UTF8String] ];
This data is finally send as a parameter in the url.
code for network communication :
postData=[postData stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *requestUrl = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"%#%#",url,postData]];
NSURLRequest *request =[[NSURLRequest alloc] initWithURL:requestUrl];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/plain"];
[operation setCompletionBlockWithSuccess:success failure:failure];
[operation start];
Also used following for escape characters:
[postData stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Error received :
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x7d51e9a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL}}, NSLocalizedDescription=unsupported URL}

I think you should use it like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *strURL = [NSString stringWithFormat:#"%#/add-product.php", apiPrefix];
[manager POST:strURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictData options:0 error:&error]; // dictData is your dictionary
NSAssert(jsonData, #"Failure building JSON: %#", error);
NSDictionary *jsonHeaders = #{#"Content-Disposition" : #"form-data; name=\"data\""}; // data is your parameter name in which you have to pass the json
[formData appendPartWithHeaders:jsonHeaders body:jsonData];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
Hope this will help....

Related

send JSON object in POST request AFNetworking , iOS

I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"input_1": #"hello world",
#"input_2": #"my#you.com",
#"input_3": #"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
}failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"%#",[error localizedDescription]);
}];
I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.
#interface AFJSONRequestSerializer : AFHTTPRequestSerializer
AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.
add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
e.g
NSString *string = [NSString stringWithFormat:#"%#?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"json == %#", json);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"%#", [error localizedDescription]);
}];
Update Params
NSDictionary *params = #{#"1": #"hello world",
#"2": #"my#you.com",
#"3": #"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:#"input_values"];
you get output of

AFNetworking 3 x-www-form-urlencoded post data

I'm trying to post data with x-www-form-urlencoded body.
Posting via postman, it is ok
But i cant do it via afnetworking 3. Here is my code
NSDictionary *parameters = #{#"login" : email,
#"password": password};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
self.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *urlString = [NSString stringWithFormat:#"%#/%#", HTTPBaseRequestURL, appendLoginUrl];
NSLog(#"URL %#\njsonString %#", urlString, jsonString);
[self POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:jsonData name:#"data"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
onSuccess(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSString *errorDescription = [NSError serverErrorMessageFromData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]];
NSInteger statusCode = [NSHTTPURLResponse errorCode:(NSHTTPURLResponse*)task.response];
NetworkRequestError *requestError = [[NetworkRequestError alloc] initWithType:
(NSHTTPURLResponse*)task.response ? NetworkRequestErrorTypeServerError : NetworkRequestErrorTypeNoConnection
description:
(NSHTTPURLResponse*)task.response ? errorDescription : nil];
requestError.statusCode = statusCode;
NSLog(#"Error from server: %#, status code = %ld, error type = %lu", requestError.errorDescription, (long)requestError.statusCode, (unsigned long)requestError.type);
onFailure(requestError);
}];
Please, help me to understand how to correctly do this. Thanks!
After commenting I finally found the answer to this. Here's my correctly functioning request now, note the addition of
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Here's the full code:
NSString *url = [NSString stringWithFormat:#"%#%#",APIBASE,APIUSERENDPOINT];
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
username, #"username",
password, #"password",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
try append custom header info ,for example:
[self.requestSerializer setValue:#" application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type];
hope it help for you.
Here . It worked with me . So easy .
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"deviceTokenIOS", #"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba",
#"message", #"Hello Dunglt",
nil
];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"db487c983ebbe7c2fb066d292bb4318175f54ab27b6b9df7871907e1d0ed62ba", #"deviceTokenIOS", #"Hello Dunglt", #"message", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:[NSURL URLWithString:url].absoluteString parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];}

Unable to post JSON Using afnetworking in ios

I am getting this error while posting json to url :
Invalid top-level type in JSON write'
I am even sending perfect JSON using afnetworking post request code But it keeps giving me error.
My code :
NSString * serviceType = #"xyz";
NSString * remarks =#"project deadline is near ";
NSString * emailId = #"xyx.live.com";
NSDictionary *params =
# {
#"serviceType" :serviceType,
#"remarks" :remarks,
#"emailId" :emailId
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager2.requestSerializer = serializer;
[manager2 POST:#"http://xyx.com" parameters:jsonString success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON_post_fzzlogin: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//here is place for code executed in success case
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending POST"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"Error: %#", error);
}];
Please help me out this regard .thanks in advance
You are trying to encode request twice because you set request serializer for AFHTTPRequestOperationManager and provide parameters as encoded JSON string. So you need to provide raw parameters if you want to use request serializer or don't use it and encode to JSON manually.
This is how you post JSON or rather NSDictionary by AFNetworking
NSDictionary *dict = #{#"Key":#"Value"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[Util urlAppend:kListOfArticleCatagory] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *responseObj = (NSDictionary *)responseObject;//casting to NSDictionary from id
NSLog(#"%#",responseObj);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Something went wrong :%#",operation.responseString);
}];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
}
You dont post JSON through AFNetworking, rather the NSDictionary as the parameters, it will get converted to JSON as you post it.

How to make Twilio api Post request with the help of AFNetworking?

I want to access Twilio api using AFNetworking. I tried number of ways but not get success. Please help me, if anyone did Tiwilo post request using AFNetworking.
Case 1: This is my native objective-c working code.
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", from, to, message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError)
{
DLog(#"Error: %#", connectionError);
completionBlock(connectionError, NO);
}
else
{
completionBlock(connectionError, YES);
}
}];
Case 2: Using AFNetorking: Code that is not working:
Code:
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSDictionary *dict = #{
#"From" : from,
#"To" : to,
#"Body" : message
};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:urlString parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success: %#", responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Related Error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x1775e660 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x175101b0 "Request failed: bad request (400)"}
Case 3: Using AFNetorking: Another Code that is also not working:
Code:
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", from, to, message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}];
[operation start];
Related Error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x177a3e70 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Thank you.
Ricky from Twilio here. First off a quick disclaimer. Making a request to Twilio directly from an iOS app requires you to embed your Twilio account credentials in the app, which is dangerous. My recommendation would be to send the SMS from a server side script that your app makes a request to in order to keep your credentials safe.
That being said, your code is really close. By default, Twilio's REST API returns XML. If you want to parse the response as it's returned by default you can update the code in version 2 to use the AFXMLParserResponseSerializer:
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
If you'd rather work with JSON then you update the Twilio URL you're making the POST request to and indicate you'd like a JSON response:
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages.json", kTwilioSID, kTwilioSecret, kTwilioSID];
Hope that helps.

responseObject is not JSON but NSInLineData for AFHTTPRequestOperationManager

Following code is to submit images through an operationQueue. The requests are all fired one by one correctly, the server response contains the image file name which client needs to get hold of. The problem is that the reponseObject for the success/failure block is not expected parsed JSON but type of NSInLineData shown in debugger. Now I suspect the code to construct the operation from the NSMutableURLRequest caused the issue. Please help.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST"
URLString:podURLString parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
BOOL success =[formData appendPartWithFileURL:imgURL name:#"images" fileName:img.path
mimeType:#"image/jpg" error:nil];
if (!success)
NSLog(#"appendPartWithFileURL error: %#", error);} error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Image Success: %#", [responseObject description]);
NSString *imagePath = [response objectForKey:#"imageFileName"];
[self.delegate networkManager:self didSubmitDeliveryImageForImageID:imagePath];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image Error: %#", error);
NSLog(#"image error: %#", [operation.responseObject description]);
NSString *imageFilePath = [operation.responseObject objectForKey:#"imageFileName"];
[self.delegate networkManager:self didFailSubmitDeliveryImageForImageID:imageFilePath];
}];
[manager.operationQueue addOperation:operation];
When you get the response as NSInLineData. It's good to go now. You can write below single line of code to get NSDictionary if it supports json format.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObjec options:0 error:nil];
Just add this line of code before your AFHTTPRequestOperation block
**operation.responseSerializer = [AFJSONResponseSerializer serializer];**

Resources