I need to make HTTP POST request, in that request I have to send some text fields and couple of files.
Every time I make the request, the files are uploaded, but I get such response.
"Success: <656d7074 79>" (aka "empty")
Here is the code, my parameter dictionaries are .
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// Append Files
NSError *error;
for (NSString *filePathsKey in filesPathsDictionary) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filesPathsDictionary[filePathsKey]] name:filePathsKey error:&error];
if (error) {
NSLog(#"%#", error);
}
}
// Text parameters
for (NSString *textParameterKey in textParamDictionary) {
[formData appendPartWithFormData:[textParamDictionary[textParameterKey] dataUsingEncoding:NSUTF8StringEncoding] name:textParameterKey];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
UPDATE:
Changed my response serializer to JSON, because I'm expecting JSON
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
And getting this error:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Related
This is the code I wrote for posting JSON to server.
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
mgr.requestSerializer = [AFJSONRequestSerializer serializer];
NSLog(#"Dictionary %#",formData);
[mgr POST:[self getFullURL:WSFormSubmit] parameters:formData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
formData Prints as:
{
FieldValueDTOs = (
{
AdditionalInfo = "";
CreateTime = "2015-09-09 10:14";
FieldValue = "";
ReportFieldValueID = 0;
ReportID = 0;
ReportTemplateFieldID = 21642;
},
{
AdditionalInfo = "";
CreateTime = "2015-09-09 10:14";
FieldValue = asdfasdf;
ReportFieldValueID = 0;
ReportID = 0;
ReportTemplateFieldID = 21643;
}
);
LocationID = 27;
ReportID = 0;
ReportLabel = "";
ReportTemplateID = 930;
ReportTime = "2015-09-09 10:14";
}
This seems to be perfect Dictionary to send it as a parameter to manager's POST:parameters:success method.
But it's returning this error when I do this. I couldn't figure out what's causing the error.
Error log in debugger:
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=0x79069f90 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x790517c0 "Request failed: bad request (400)"}
formData must be NSDictionary object
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:60];
[manager POST:[self getFullURL:WSFormSubmit]
parameters:formData
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",newStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Hope this works, you can set values for json in header field
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
mgr.requestSerializer = requestSerializer;
[mgr POST:[self getFullURL:WSFormSubmit] parameters:formData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:"<Your Host URL>" parameters:<Params as Dictionary> success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
// *** Perform success action ***
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// *** perform failure action ***
}];
you forgot to set contentType for your request which is JSON and make sure your API accepts JSON and POST data as input otherwise it will not work.
i tried it but didn't work in AFNetworking only showing parameters error
but i used postman to check and when i send data via key and value it showing error but from raw data i send {"register_id":"3"}
then it will show me data so how to post parameter like this in AFNetworking.
using This Link
http://www.icubemedia.net/visitorbook/display_all.php
is any one can help me for that how to post that data
log error is:
2015-06-19 14:05:08.078 DemoAFNetworking[72771:1160924]
{"msg":"parameter missing!"}
Indeed there are no parameters missing, the fact that the request worked in Postman was the key. On the one hand, you should be trying to POST to that URL, not GET. On the other hand, since you are sending a JSON, you need the appropriate serializer.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//JSON Serializer
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"register_id": #"3"};
[manager POST:#"http://www.icubemedia.net/visitorbook/display_all.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Check this example on how to do a GET with simple parameter with AFNetworking 2.0:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager GET:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT 1: added JSON serializer ;)
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:
{
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VlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwibWVyY2hhbnRBY2NvdW50SWQiOiI2ejl3eGtkanlyNnQzbmg1IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sImNvaW5iYXNlRW5hYmxlZCI6ZmFsc2UsIm1lcmNoYW50SWQiOiJ6cWQ5ZHBqZmZkc2s3eG55IiwidmVubW8iOiJvZmYifQ==";
}
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.");
}
I am trying to upload a image using AFHTTPSessionManager through REST API call.
following are my code
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager.requestSerializer setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
[manager POST:#"http://localhost:8888/uploadImage/100" parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData name:#"avatar" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"success:%#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error:%#", error);
}];
Response is going to field block and getting following error
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=0x9cbc690 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x9cbaf00 "Request failed: length required (411)"}
Any one have idea on this issue ?
Thanks
+(void)uploadImageData : (NSString *)url parameters:(NSDictionary *)dparameters imageData:(NSData *)dimageData success: (void (^) (NSDictionary *responseStr))success failure: (void (^) (NSError *error))failure
{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *op = [manager POST:url parameters:dparameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:dimageData name:#"image" fileName:#"photo11.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
failure(error);
}];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[op start];
}
The error
JSON text did not start with array or object and option to allow
fragments not set
Indicates that the server sent JSON with a fragment which isn't supported by the iOS JSON parser by default. You can enable it by setting the AllowFragments option for readingOptions on your AFJSONResponseSerializer.
Try to add (Swift)
manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
This solves for me.
I'm working on a mobile app that takes personal information from users then saves it to the php server. I'm having a problem on the data with array of dictionaries, how do I fix this?
The sample data that the mobile app sends to the server looks like this, see the work_experience, it's an array of dictionaries:
Don't mind the data values, it's taken on different times, mind the data structure in work_experience
It becomes like this when it reaches the server:
This is how the work_experience gets saved, which is wrong:
This is my post request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
php function that receives the post request:
$params = $this->params()->fromPost();
$userId = $this->getUsersTable()->saveUserInfo($params);
$this->getSkillsTable()->saveSkills($params['skillset'], $userId);
$this->getWorkExperienceTable()->saveWorkExperience($params['work_experience'], $userId);
$view = new JsonModel($params);
return $view;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You are limiting the app to only accept responses with header text/html, which is not correct because you are looking for json response. And you need to set the requestSerializer to a AFJSONRequestSerializer instance because the default is AFHTTPRequestSerializer