This is my Code:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dict = #{#"body":json};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://abc/" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *myString = [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding];
NSLog(#"Error: %#", myString);
}];
But i am Getting Error Like This
body=%7B%22pincode%22%3A%22gfgfgf%22%2C%22mobile%22%3A%221111%22%2C%22password%22%3A%22rwerew%22%2C%22profile_pic%22%3A%22%22%2C%22social_accesstoken%22%3A%22%22%2C%22sponsor_choice%22%3A3%2C%22sponsor_id%22%3A%22%22%2C%22social_provider%22%3A%22Normal%22%2C%22email%22%3A%22ghffh%22%2C%22gender%22%3A1%2C%22name%22%3A%22narendra%22%2C%22nickname%22%3A1233%2C%22country%22%3A%22Japan%20%28JPY%29%22%2C%22fromLogin%22%3A%22%22%2C%22methodName%22%3A%22signup%22%2C%22birth_date%22%3A%2208-06-01%22%7D
Can any one suggest me on this kind...
There is no need to convert error to encoded string....
First of all clear that.. which type of parameter you needed..
and then try this code for simple posting data:
(Make related changes according to your parameters needed)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *param = # {#"body":json};
[manager POST:URL_HERE parameters:param
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Related
I want to try post parameter in the following API but the parameter is not getting passed properly, and the response received gives the message that, data is required. So can anyone please help to sort out this problem.
my url is
forapp.com/api/getContacts.php?data=[
{"name":"abc","phone":"1234567890"},{"name":"Kate
Bell","phone":"9925992599"} ]
so how i can pass this type of request to the api
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
NSLog(#"Dict %#",params);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
just add
Step-1
// create the dictionary of {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} this
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
Step-2
//create the one array of this output [ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
NSMutableArray *arr = [NSMutableArray arrayWithObjects:params,nil];
Step-3
// convert your object to JSOn String
NSError *error = nil;
NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:objectsInCart
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];
Step-4
//create the another one dictionary for send the data for like data=[ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
NSDictionary *pardsams = #{#"data": createJSON};
Step-5
// finally start your request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSLog(#"Dict %#",pardsams);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:pardsams success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
as per this url
forapp.com/api/getContacts.php?data=[ {"name":"abc","phone":"1234567890"},{"name":"Kate Bell","phone":"9925992599"} ]
You should implement like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"name": #"hello",
#"phone": #"1234567890"};
NSLog(#"Dict %#",params);
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://forapp.com/api/getContacts.php" parameters:#{#"data": #[params]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Add following:
// httpClient is a subclass of AFHTTPRequestOperationManager or AFHTTPSessionManager
httpClient.requestSerializer = AFJSONRequestSerializer;
And also check your post array does not include any other object. It just include array.
Here's my question:
NSDictionary *parameters = #{#"type": #"5", #"xq": #"a", #"apid": #"b", #"apsecret": #"c", #"astoken": #"d"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"text/plain; charset=UTF-8"] forHTTPHeaderField:#"Content-Type"];
if i use GET :
[manager GET:#"http://127.0.0.1/123.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error : %#", error);
}];
i can get $_GET['parameters'] value
but when i use POST :
[manager POST:#"http://127.0.0.1/123.php" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error : %#", error);
}];
i always get $_POST['parameters'] value is null.....
am i doing something wrong in the setting?
Change your 4th line of 1st code snippet to,
[manager.requestSerializer setValue:[AFJSONRequestSerializer serializer]];
sorry for all,
i found it's can work
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://127.0.0.1/123.php"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"123.php"
parameters:parameters
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error : %#", error);
}];
I have a put request that I am trying to achieve. The problem I am having is it isn't sending the correct raw body over to the server form/post parameter. What I am expecting is a raw body that is {"questions":[{"type":"control_head"}]}, instead I am getting questions[][type]=control_head any tips or suggestions are appreciated.
NSString *jsonString = #"{\"questions\":[{\"type\":\"control_head\"}]}";
[self createForms:jsonString];
- (void) createForms : (NSString *) form
{
[self executePutRequest:#"user/forms" params:form];
}
- (void) executePutRequest : (NSString *) url params : (NSString *) params
{
NSString *urlStr = [NSString stringWithFormat:#"http://requestb.in/13oujhot"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager PUT:urlStr parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
SBJsonParser *jsonparser = [SBJsonParser new];
id result = [jsonparser objectWithString:[operation responseString]];
if ( self.delegate != nil && [self.delegate respondsToSelector:finishSelector] ) {
[self.delegate performSelector:finishSelector withObject:result];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
if ( self.delegate != nil && [self.delegate respondsToSelector:failSelector] ) {
[self.delegate performSelector:failSelector withObject:[operation error]];
}
}];
}
Copied From here
Updated again for AFNetworking 2.0 - see bottom
For AFNetworking 1.0:
NSURL *url = [NSURL URLWithString:#"https://mysite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://mysite.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
you can use afnetworking framework, it will help you.
http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
NSString *str_URL = [NSString stringWithFormat:#"YOUR URL"]];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
Your Value,KEY_Name,
nil];
AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
[Manager PUT:str_URL parameters:parameters
success: ^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"%#", error.description);
}];
This question is already answered at many places but no solution is working for me! I m using code for AFNetworking as following
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSDictionary *parameters=#{#"Key1":#"Value1",#"Key2":#"Value2"};
// NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"https://www.MyURL.com/index.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Error :
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x7a2a03b0 {NSErrorFailingURLKey=https://www.MyURL.com/index.php, NSErrorFailingURLStringKey=https://www.MyURL.com/index.php}
I got no luck for above request.
I do not know what is wrong with my code in POST Request, GET Request is working fine in the AFNetworking.
Try this one :
NSDictionary *dictParameters = parameter here
//create url
NSString *strURL = [NSString stringWithFormat:#"url here"];
NSLog(#"loginurl : %#",strURL);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *apiRequest = [manager POST:strURL parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSData *jsonData = (NSData *)responseObject;
NSError * parsedError = nil;
id *value = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&parsedError];
if (parsedError == nil)
{
//Successfull
}
else
{
NSLog(#"wrong while parsing json data");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error : %#",[error description]);
}];
//start request right now
[apiRequest start];
EDIT : Just Formatted
I am struggling for hours to get AFMultipartFormData to work...
I need to signup a user by sending his info and his picture.
The documentation i have from the back-end developer to achieve this is:
The required parts are: 'registration' with content type 'application/json' and 'pic' with content type image/*
I tried several ways to do this without any success. What is wrong with the code below?
-(void)serverAuthentication {
NSDictionary *jsonDictionary = #{#"clientId":#"someClientId3", #"name":#"Pantelis", #"email":#"someuser#gmail.com", #"password":#"1234567"};
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"sampleJohnTsioris"], 0.5);
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
if (!jsonData) {
NSLog(#"JSON ERROR");
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(#"JSON OUTPUT: %#",JSONString);
}
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:#"http://someserver.com/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:jsonData name:#"registration"];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"photo.jpg" mimeType:#"image/*"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];
}
The error i get:
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: unsupported media type (415)"
You can't change the content type of the request. It must be "multipart/form-data".
You need to make sure the "registration" part has a mime type of "application/json".
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://someserver.com/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:jsonData name:#"registration" fileName:#"user.json" mimeType:#"application/json"];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];
I found out the solution. As Jeffery Thomas wrote, you can't change the content type of the request, and there was the problem. Specifically, there was no problem at all sending the image but the json object which needed the name "registration" AND the content-type and i couldn't find the proper way to pass both. So, I made up the headers needed to do that (pass the content-type and the name).
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"http://vext.dsigned.gr:8080/auth/account/email" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithObjectsAndKeys: #"application/json; charset=UTF-8",#"Content-Type", #"form-data; name=\"registration\"",#"Content-Disposition", nil];
[formData appendPartWithHeaders:headers body:jsonData];
[formData appendPartWithFileData:imageData name:#"pic" fileName:#"avatar.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation=%#",operation);
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"operation=%#",operation);
NSLog(#"Error: %#", error);
}];