AFNetworking Error: "Expected status code in (200-299), got 404" - iphone

My code:
NSURL *url = [NSURL URLWithString:#"http:testurl.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSString *email = #"test#test.com";
NSString *password = #"test";
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
email, #"email",
password, #"password",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:AFJSONParameterEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
Even though I know the server is expected a POST I tried GET and PUT too and still received the same error. I also have checked the URL 100 times. Any ideas on what's causing the error?
Thanks!!

Go to the URL made by putting http:testurl.com and /myobject together in your browser. 404 means that page or resource does not exist.
Try also moving the slash to the baseUrl, i.e. baseURL to http://testurl.com/ and postPath to myobject see this issue

Your base URL is malformed.
Change this: "http:testurl.com"
To this: "http://testurl.com"

Related

Send the image on API using post method from imagepicker

I want to make a registration form, here I have taken all UITextField data in string and send on the api using post method but I don't know how to send image on api with all data?
Try Following code Snippet
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL: [NSURL URLWithString:#"Your URL"]];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"YourValue",#"ValueName",#"YourValue",#"ValueName", nil];
NSData *imageData = UIImagePNGRepresentation(img_Picture);
[manager POST:#"Your URL" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"logo" fileName:#"image.png" mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
}];
Where parameters contains all your textfield's data.
And Logo is image parameter name which is used in api coding.

Iphone - AFNetworking Login Form always returns 404

I'm having troubles with AFNetworking, decided to use it since ASIHTTP is long deprecated, and I'm trying to use it in a login form request, but the response code is always -1011.
here is my code :
NSString *urltest = [NSString stringWithFormat:#"%#%#/", SERVER_ADDRESS, API_ADDRESS];
NSURL *url = [NSURL URLWithString:urltest];
NSLog(#"url address : %#",url);
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.allowsInvalidSSLCertificate = TRUE;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
_email.text, #"email",
_password.text, #"password",
nil];
// Here I try doing my login request using AFHTTPRequestOperation
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"/auth/login" parameters:params];
[request setValue:#"application/x-www-form-urlencoded; charset=UTF8" forHTTPHeaderField:#"Content-Type"];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
// Here I try doing my login request using the postPath:parameters: method
[httpClient postPath:#"/auth/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self performSegueWithIdentifier:#"AuthOK" sender:self];
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request failed with code %d for %# for request : %#",error.code , error.localizedDescription,httpClient.baseURL);
}];
And none of these two methods are working, I'm guessing I'm doing something wrong somewhere
btw, the server I login to, has an unsigned ssl certificate, but I handled the error by adding
#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 1
in AFURLConnectionOperation.h
I use Charles to monitor http requests, and it gives me a "SSLHandshake: Remote host closed connection during handshake"
My app runs with iOS 5.
Anyone has insights on this?
Leo
Well my solution was to initialize my request with an empty url and then in the postPath, put the whole address.
You need to install Charles' SSL Certificate on your device to decrypt SSL traffic
http://www.charlesproxy.com/documentation/faqs/ssl-connections-from-within-iphone-applications/

upload Video to Facebook using iOS6 Social Framework

I want to publish a video file to facebook. Previously I used the Facebook iOS SDK3.0 and it works. However, for iOS6 Social Framework, there is problem.
__block ACAccount * facebookAccount;
ACAccountStore* accountStore = [[ACAccountStore alloc] init];
NSDictionary *options = #{
ACFacebookAppIdKey: #"MY APP ID",
ACFacebookPermissionsKey: #[#"publish_actions", ],
#"ACFacebookAudienceKey": ACFacebookAudienceFriends
};
ACAccountType *facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSLog(#"access to facebook account ok %#", facebookAccount.username);
NSData *videoData = [NSData dataWithContentsOfFile:[self videoFileFullPath]];
NSLog(#"video size = %d", [videoData length]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType" ,
#"Video title", #"title",
#"Video description", #"description",nil];
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:requestURL
parameters:params];
request.account = facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response,NSError * error){
NSLog(#"response = %#", response);
NSLog(#"error = %#", [error localizedDescription]);
}];
} else {
NSLog(#"access to facebook is not granted");
// extra handling here if necesary
}
}];
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSConcreteData
_fastCharacterContents]: unrecognized selector sent to instance 0x2097ead0'
Here is my research:
First, the video data cannot be part of the parameter list, since it will render the SLRequest invalid and that is the crash you are experiencing.
The video data must go in the multi part section of the request.
Now,there is a need to associate the parameters with the multipart data and that is the tricky part. So it is necessary to use the source attribute to make that link.
Source requires a URL in a string format set it in the parameters and set the same value in the filename field in the multipart request.
That should do it.
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
NSURL *videoPathURL = [[NSURL alloc]initFileURLWithPath:videoPath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:videoPath];
NSString *status = #"One step closer.";
NSDictionary *params = #{#"title":status, #"description":status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
[request addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[videoPathURL absoluteString]];
I'm working the same issue. I think your error is from ARC and NSData *videoData gets deleted before the return from performRequestWithHandler.

AFNetworking POST to REST webservice

Brief backstory, our previous developer used ASIHTTPRequest to make POST requests and retrieve data from our webservice. For reasons unknown this portion of our app stopped working. Seemed like good enough time to future proof and go with AFNetworking. REST webservice runs on the CakePHP framework.
In short I am not receiving the request response string using AFNetworking.
I know the webservice works because I am able to successfully post data and receive the proper response using curl:
curl -d "data[Model][field0]=field0value&data[Model][field1]=field1value" https://example.com/api/class/function.plist
Per the previous developer's instructions I came up with the following.
#import "AFHTTPRequestOperation.h"
…
- (IBAction)loginButtonPressed {
NSURL *url = [NSURL URLWithString:#"https://example.com/api/class/function.plist"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[usernameTextField text] forHTTPHeaderField:#"data[User][email]"];
[request setValue:[passwordTextField text] forHTTPHeaderField:#"data[User][password]"];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(#"response string: %# ", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
}];
[operation start];
}
output:
operation hasAcceptableStatusCode: 200
response string: a blank plist file
attempted solution 1:
AFNetworking Post Request
the proposed solution uses a function of AFHTTPRequestOperation called operationWithRequest. However, when I attempt to use said solution I get a warning "Class method '+operationWithRequest:completion:' not found (return type defaults to 'id'"
attempted solution 2: NSURLConnection. output: I'm able to print the success log messaged but not the response string.
*update - returns blank plist.
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = #"data[User][email]=username#example.com&data[User][password]=awesomepassword";
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
// *update - returns blank plist
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData %#",str);
if (error == nil && response.statusCode == 200) {
// Process response
NSLog(#"success");//returns success code of 200 but blank
NSLog(#"resp %#", response );
} else {
// Process error
NSLog(#"error");
}
These are the essential (stripping out conditions I've made for my own use) lines that ended up satisfying my request to the web service. Thanks for the suggestions #8vius and #mattt !
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"https://www.example.com/api/class"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"https://www.example.com/api/class/function" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Use AFHTTPClient -postPath:parameters:success:failure:, passing your parameters (nested dictionaries/arrays are fine). If you're expecting a plist back, be sure to have the client register AFPropertyListRequestOperation.
In any case, setValue:forHTTPHeaderField: is not what you want here. HTTP headers are for specifying information about the request itself; data is part of the request body. AFHTTPClient automatically converts parameters into either a query string for GET requests or an HTTP body for POST, et al.

unable to parse json response from google

I am trying to parse Json response from This URL. I have used SBJsonParser, MTJSON and another parser but i am getting NULL in all three case.
apiUrlStr = #"http://maps.google.com/maps?output=dragdir&saddr=Delhi&daddr=Mumbai+to:hyderabad";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
SBJsonParser *json = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dictionary = [json objectWithString:apiResponse];
NSLog(#"dictionary=%#", [json objectWithString:apiResponse]);
2011-12-09 16:59:01.226 MapWithRoutes[2523:207] dictionary=(null)
Plz suggest me something
Oke if checked the url you gave with JSONlint.com and the JSON is not valid. thus can not be parsed by any library.
If you used JSONkit you can supply a NSError object with the parse call to see what went wrong:
NSError *error = nil;
NSDictionary *dictionary = [apiResponse objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if (!dictionary) {
NSLog(#"Error: %#", error);
}