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.
Related
I am unable to get the response from api as the response is quite large. Below code gives internal server error but on rest client runs fine.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager GET:constantString parameters: nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"POST data JSON returned: %#", responseObject);
jsonArrayNew = responseObject;
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
dispatch_async(dispatch_get_main_queue(), ^{
});
});
Im using salesforce live agent rest api in ios app, trying to request chat but always fail with 400 request is not a valid ChasitorInit
NSDictionary *parameters =#{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#[],
#"prechatEntities" :#[],
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = serializer;
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:ChasitorInit_path parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Im using Afnetworking v3 ios8
The request body should be
{
"sessionId": "8f1cfb18-fbd1-4487-90d-e98c0a84e165",
"organizationId": "00D58000000OwMB",
"deploymentId": "57258000000L1mj",
"buttonId": "57358000000L24F",
"userAgent": "",
"language": "en-US",
"screenResolution": "1900x1080",
"visitorName": "Test Visitor",
"prechatDetails": [],
"prechatEntities": [],
"receiveQueueUpdates": true,
"isPost": true
}
What im i doing wrong ? Plz correct me !!
400 Bad request means, you didn't form the request the way server expects.
Check the server logs for whats the issue...
May be it needs data in another form..
and try to check that,you are not passing null value to server..
Try like that:
NSString *Loginurl = [NSString stringWithFormat:#"http://Enter your URL Here"];
NSDictionary *params = #{ #"SessionId" :self.sessionId,
#"OrganizationId" :ORG_ID,
#"deploymentId" :DEPLOYEMENT_ID,
#"buttonId" :BUTTON_ID,
#"userAgent" :USER_AGENT,
#"language" :LANG,
#"screenResolution" :SCREEN_RES,
#"visitorName" :#"Test Visitor",
#"prechatDetails" :#{},
#"prechatEntities" :#{},
#"receiveQueueUpdates":#"true",
#"isPost" :#"true"
};
NSLog(#"Sent parameter to server : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager.requestSerializer setValue:self.sessionKey forHTTPHeaderField:X_LIVEAGENT_SESSION_KEY];
[manager.requestSerializer setValue:#"null" forHTTPHeaderField:X_LIVEAGENT_AFFINITY];
[manager.requestSerializer setValue:#"1" forHTTPHeaderField:X_LIVEAGENT_SEQUENCE];
[manager.requestSerializer setValue:API_V forHTTPHeaderField:X_LIVEAGENT_API_VERSION];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
_str=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#",_str);
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
#pragma mark-DataFromServer
-(void)getdata:(NSDictionary*)RegisterData
{
}
I got the same error in my app. I resolve it by removing request and response Serializer. Only instantiate manager and called post method with parameter.
reqManager = [AFHTTPRequestOperationManager manager];
[reqManager POST:URLString parameters:parameters progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
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.}
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 = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJhMjg2OGVjY2FmZjNjMTQ0M2Y4MTg2MjQ4NDFhZDIyZGM3MWFhOTQ0MmFiMTY2NWVlNWY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2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwibWVyY2hhbnRBY2NvdW50SWQiOiI2ejl3eGtkanlyNnQzbmg1IiwiY3VycmVuY3lJc29Db2RlIjoiVVNEIn0sImNvaW5iYXNlRW5hYmxlZCI6ZmFsc2UsIm1lcmNoYW50SWQiOiJ6cWQ5ZHBqZmZkc2s3eG55IiwidmVubW8iOiJvZmYifQ==";
}
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.");
}
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