I am developer iOS. I have a problem about AFHTTPRequestOperationManager request POST to server(JBoss) Java. When I request POST with Multipart is good response, and not problem. But, when I request POST only string to server, server show me error:
11:57:19,815 ERROR [UserRest] Problem on login email: null password:
null 11:57:19,817 ERROR [STDERR] java.lang.Exception: MISSING ARGUMENTS
This show me, send parameters null. This method:
AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
I don't understand, why send parameters null.. My code is:
NSString *strURL = #"http://YOUR_IP/YOUR_PATH/login";
__block const NSString *strResultResponse = #"";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = NO;
AFJSONRequestSerializer *serializerRequest = [AFJSONRequestSerializer serializer];
[serializerRequest setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
AFJSONResponseSerializer *serializerResponse = [AFJSONResponseSerializer serializer];
serializerResponse.readingOptions = NSJSONReadingAllowFragments;
serializerResponse.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.requestSerializer = serializerRequest;
manager.responseSerializer = serializerResponse;
NSDictionary *parameters = #{#"email":#"xxxxxx#xxxx.xxxx",#"password":#"xxxx"};
[manager POST:strURL parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", operation.responseString);
}];
I tried many ways, but not result. Please help me.
Related
I've a big problem, I'm trying to send an array of dictionary with afnetworking, that's my code:
checkDeliveryParams = #{#"cart_total":#(cart_total),#"shipping":#{#"address":[User sharedInstance].shipping_city,#"country":#"IT",#"postcode":[User sharedInstance].shipping_postcode,#"state":[User sharedInstance].shipping_provincia},#"user_id":#([User sharedInstance].user_id),#"cart_contents":temp};
cart total it's an array like this
(
quantity:1
product_id:2
)
but server receive something like this
(
quantity:1
),
(
product_id:2
)
my request code is
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}
I've tried a lot of method, I've tried to set nsjonserializer, "application/json", I've already tried to use NSURLSessionDataTask...
Sorry for my English, someone can help me ?
the common manager call in [rest commonManager] is defined in this method
+(AFHTTPRequestOperationManager *)commonManager:(NSString *)path sendAuthToken:(BOOL)sendToken{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.securityPolicy.allowInvalidCertificates = NO;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
if([Session isOpen] && [Rest authorizationRequiredForPath:path] && sendToken){
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [Session token]] forHTTPHeaderField:#"Authorization"];
}
return manager;
}
that's how I send parameters in get call
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}
I am trying to connect to an Api but it is using x-www-form-urlencoded ...and i am using this code .Plz tell me the correct method
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = nil;
manager.securityPolicy = securityPolicy;
[manager POST:[NSString stringWithFormat:#"#"%#%#phone=%#&password=%#",BASE_URL,API_LOGIN,phone,password]
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
successBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Server Error : %#", operation.responseString);
errorBlock(error);
}];
}
I think you should try to set the http header for 'x-www-form-urlencoded' to communicate with your backend:
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
If this does not fix your errors, then try to validate your json object.
You could also have a look to this question: AFNetworking 3 x-www-form-urlencoded post data
There are other questions with similar titles but none of them helped me. I've to send a PUT request to server in order to change the status of appointment so I've made this method -(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID In which I'm setting the URL and Parameters as
NSString *string = [NSString stringWithFormat:#"%#/API/Appointments/3",BaseURLString];
NSDictionary *para = #{
#"AppointmentStatusId":statusID,
#"ID":appointmentID
};
Then I've made URL request as
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"PUT" URLString:string parameters:para error:nil];
After that I'm setting the header for an authorization token as
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userToken"]];
[req setValue:token forHTTPHeaderField:#"Authorization"];
So finally I'm calling it as
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(#"Respose Object: %#",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
NSLog(#"Error: %#", error.localizedDescription);
}
}] resume];
Now it is successfully sending the data to the server but as a response I'm getting
Error: The data couldn’t be read because it isn’t in the correct
format.
I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.
try to use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Try following code using Afnetworking 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
self.responseHandlers(YES,responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
self.responseHandlers(NO,nil);
}];
AFNetworking response failure block is being called when I get status code 200. How can I make the success be called instead?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.clientToken = responseObject[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
Look at the value of error. It will tell you why the connection failed. "Failure" in this context has nothing to do with the status code. Returning "404" is still a "success." Failure means you were unable to complete the operation.
use acceptableStatusCodes as follows:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [TimeoutAFJSONRequestSerializer serializer];
NSMutableIndexSet* codes = [[NSMutableIndexSet alloc] init];
[codes addIndex: 200];
manager.responseSerializer.acceptableStatusCodes = codes;
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
I run this code and it work find.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:nil];
self.clientToken = json[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
responce is:
json:
{
customerID = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJhMjg2OGVjY2FmZjNjMTQ0M2Y4MTg2MjQ4NDFhZDIyZGM3MWFhOTQ0MmFiMTY2NWVlNWY1YjJkODdiOTVhYzBjfGNyZWF0ZWRfYXQ9MjAxNS0wNS0xNFQxMzoyMDowNi45NjE2NDQxNzArMDAwMFx1MDAyNm1lcmNoYW50X2lkPXpxZDlkcGpmZmRzazd4bnlcdTAwMjZwdWJ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mxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwibWVyY2hhbnRBY2NvdW50SWQiOiI2ejl3eGtkanlyNnQzbmg1IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sImNvaW5iYXNlRW5hYmxlZCI6ZmFsc2UsIm1lcmNoYW50SWQiOiJ6cWQ5ZHBqZmZkc2s3eG55IiwidmVubW8iOiJvZmYifQ==";
}
It may be work for you.
If you check your error in failure block it clearly say that invalid content type. You need to set the content type of the manager as follows
manager.requestSerializer = [AFJSONRequestSerializer serializer];
try this
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
and in success block
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:manager.responseData options:kNilOptions error:nil];
self.clientToken = dic[#"customerID"];
NSLog(#"Client Token received.");
}
How do I send a POST request with AFNetworking 2.0 with all the parameters in the URL like such:
http://www.myserver.com?api_key=something&lat=2.4&radius=100
Right now I have:
NSString* query = #"http://example.com?name=param&date=param";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
[manager POST:query parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But it's not working, I get this error back:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
The previous best answer was to get the backend to change and accepts parameters in the body. Thats the preferred method but sometimes some of us are stuck using backends that can't change so I offer this solution....
In the class AFURLRequestSerialization there is a property called HTTPMethodsEncodingParametersInURI and that is an NSSet that contains the http methods that are allowed to use params in the uri GET, HEAD, and DELETE by default.
You could override that and include POST as well.
in AFURLRequestSerialization.m lines 462 has an if statement that checks self.HTTPMethodsEncodingParametersInURI property contains POST. if it doesn't (as it doesn't by default), it will put the parameters in the body.
You can comment out that id statement for a quick test.
To get it to work I recommend overwriting the HTTPMethodsEncodingParametersInURI property.
when setting up your AFHTTPSessionManager it should look like this...
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.httpBaseUrl]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", whatever other http methods you need here....]];
this should allow for sending a parameters in the uri of a POST. worked for me, hope it helps someone else
#import "AFNetworking.h"
...
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"param1": value1,
#"param2": value};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://domain.com/backend.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
try this
I've had the same problem with you.
Other people's answers seem to be accurate.
The cause of the error is:
when you init NSUrl with parameters such as http:www.baidu.com/api?id=1&name=我,it needs you to encode your urlString with utf-8
such as :
//解决奇葩需求:请求方式为post时,url带?id=1之类。主要原因是url带中文的时候url初始化失败
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
Hope to help you!
can you try this.
NSString* apiURL = #"http://example.com"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:apiURL]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
NSDictionary *parameters = #{#"name":#"John",#"date":"27/12/2013"};
AFHTTPRequestOperation *apiRequest = [manager POST:#"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog#"response ---%#,responseObject";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[apiRequest start];
I was able to do this by creating the string like this:
NSString *relativeURL =[NSString
stringWithFormat:#"/reward/commit?deviceUUID=%#&rewardID=%#",[[Client
sharedInstance] deviceUUID],self.rewardID];
and then passing it as the query. I had to set the requestSerializer and responseSerializer as follows:
client.requestSerializer = [AFJSONRequestSerializer serializer];
client.responseSerializer = [AFHTTPResponseSerializer serializer];
Worked for me once I left the manager.requestSerializer property alone and let it be the default (AFHTTPRequestSerializer).
The service i was POSTing to, was seemingly expecting UTF8 encoded body parameters.