Requirements on connecting to https - ios

I'm trying to connect using AFNetworking to API that is under https address. I keep getting 404 since the old app, based on ASIHTTPRequest is able to connect.
Do I have to implement certificate file into app somehow? What else should be provided?

Basically you have to add nothing, you only need to add http basic auth credentials if needed. This is how i usually connect to a https api with http basic auth.
//Base URL
NSURL *requestPasswordURL = [NSURL URLWithString:BASEURL];
//Http client with server credentials
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:requestURL];
[httpClient setAuthorizationHeaderWithUsername:#"user" password:#"password"];
//Set request parameters for example email
NSDictionary *params = #{#"email": email};
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:API_REQUEST parameters:params];
request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
//Prepare request
AFHTTPRequestOperation *request = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[requestPasswordOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Your code
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Your Code
}];
//call start on your request operation
[request start];

Related

IOS sending post method data can access in php as get method

I am very new to iOS. I am trying to send data through post method to PHP. In PHP it can't take data like $_POST['data'], but it takes $_GET['data']. My iOS code is as follows.
NSString *strURL = [NSString stringWithFormat:#"http://example.com/app_respond_to_job?emp_id=%#&job_code=%#&status=Worker-Accepted&comment=%#",SaveID2,txtJobcode1,alertTextField.text];
NSURL *apiURL = [NSURL URLWithString:strURL];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:apiURL];
[urlRequest setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
_receivedData = [[NSMutableData alloc] init];
[connection start];
NSLog(#"URL---%#",strURL);
Can someone explain why is that, it will be very helpful.
Please Download this file https://www.dropbox.com/s/tggf5rru7l3n53m/AFNetworking.zip?dl=0
And import file in your project
Define in #import "AFHTTPRequestOperationManager.h"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"Your Url"]];
NSDictionary *parameters = #{#"emp_id":SaveID2,#"job_code":txtJobcode1.text,#"status":alertTextField.text};
AFHTTPRequestOperation *op = [manager POST:#"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[responseObject valueForKey: #"data"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
because you send your data via query string in url
i think it will work if you try to pass data in your request's body:[urlRequest setHTTPBody:...]
POST parameters come from the request body, not from the URL string. You'll need to:
Call setHTTPBody on the request and provide the URL-encoded string (sans question mark, IIRC) as the body data
Call setValue:forHTTPHeaderField: to set the Content-Type to application/x-www-form-urlencoded
Either remove the call to [connection start] or use initWithRequest:delegate:startImmediately: so that you aren't starting the connection twice.
That last one is kind of important. You can get strange results if you try to start a connection twice. :-)

iOS connect to Magento using OAuth

I am trying to connect to Magento REST with OAuth authentication on iOS. I already have: consumer_key, consumer_secret, token, token_secret and the url. With Chrome Rest Client I can connect without problems but in iOS using OAUthiOS library I can not. This library has some example to authenticate to Facebook and Twitter but what I need is to connect to my rest services.
What I have tried so far:
NSString *key = #"Authorization";
NSString *value = #"OAuth realm="http://www.myweb.com/",oauth_consumer_key="xxxx",oauth_token="yyyyy",oauth_nonce="zzzz",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1111111",oauth_version="1.0",oauth_signature="wwwwww"";
request = [[OAuthIORequest alloc] init];
[request addHeaderWithKey:key andValue:value];
[request get:PRODUCTS_SERVICE success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
NSLog(#"body %#", body);
}];
But nothing happend. What should I do? Is there any framework better?
Thanks!
I have resolved this issue using another framework: AFNetworking and AFOAuth1Client instead of OAUthiOS.
AFOAuth1Client * client = [[AFOAuth1Client alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL] key:CONSUMER_KEY secret:CONSUMER_SECRET];
[client setOauthAccessMethod:#"GET"];
[client setSignatureMethod:AFHMACSHA1SignatureMethod];
[client setDefaultHeader:#"Accept" value:#"application/json"];
[client setAccessToken:[[AFOAuth1Token alloc] initWithKey:TOKEN secret:TOKEN_SECRET session:nil expiration:nil renewable:FALSE]];
NSMutableURLRequest * request =[client requestWithMethod:#"GET" path:PRODUCTS_SERVICE parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];

AFNetworking: Get JSON Value From Http Response

I am primarily an android developer and really new to IOS. I am using AFNetworking 1.0 since I am working with an existing source and I am sending a standard http Post request and returning the data like so:
//Sending the post request and getting the result
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://testsite.org/mobile_app"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://testsite.org/mobile_app/studentregister.php"
parameters:#{#"username":username, #"displayname":displayname, #"password":password, #"passwordc":passwordc, #"email":email, #"teacherCode":teacherCode}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
the response should contain the JSON data which looks like this according to burp suit:
{"userCharLimit":"Your username must be between 5 and 25 characters in length"}
{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}
{"passLimit":"Your password must be between 8 and 50 characters in length"}
{"emailInvalid":"Not a valid email address"}
{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.
How can I get those JSON values? I have seen a lot of AFNetworking 2.0 JSON examples and sending JSON Post request but I can seem to find much for version 1.0 let alone getting the values form a standard post request.
Any ideas or resources?
All you should need is to change your code to register a AFJSONRequestOperation instead of AFHTTPRequestOperation.
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
Then you can use this method on AFHTTPClent to create the operation which will actually be of type AFJSONRequestOperation.
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];

AFNetworking 2.0 / AFHTTPRequestOperation application/x-www-form-urlencoded

Been using AFNetworking 2.0 for the past two projects for a medium sized project to great success.
This one call though, to post a user' login info, keep failing on me (server states incorrect login & password, login is the email, we've check on the server and the values are the same I'm trying to send)
The server developer does not handle iOS / ObjC (java / mongoDB guy), All I'm giving is a URL and the parameters I need to pass with Content-Type = application/x-www-form-url-encoded
I read somewhere that characters such as # (in the email) could cause problems
Could anyone with more experience than me here chip in? my operation creation method is below, any help is TRULY appreciated.
-(AFHTTPRequestOperation *)loginUserWithParameters:(NSDictionary *)loginParameters
{
/*
parameters dictionary:
email
psw
deviceToken
*/
NSString *url=SERVER_USER_LOGIN;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]];
// [httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request=[httpClient requestWithMethod:#"POST" path:nil parameters:nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:loginParameters options:kNilOptions error:nil];
[request setHTTPBody:jsonData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[AFNetworkActivityIndicatorManager sharedManager].enabled=YES;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return operation;
}
Actually you say with your code that you will send url-encoded data to your server, but you are overriding the postBody of your request with custom data. So you should create your request with:
NSMutableURLRequest *request=[httpClient requestWithMethod:#"POST" path:nil parameters:loginParameters];
And you should delete below lines:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:loginParameters options:kNilOptions error:nil];
[request setHTTPBody:jsonData];
I think above changes will be enough.

SDK and AFNetworking

I am trying to write code for an SDK. I need to make API calls.
I am using AFNetworking 2.0 to send a POST request to the server:
NSDictionary * params = [self formDictionaryFromCard: card];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString: [self apiUrl] parameters: params];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"Firefox" forHTTPHeaderField:#"User-Agent"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
successBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
errorBlock(error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
So far I have the above, but I can't figure out how to pass in headers (like the authorization header), or provide support for https.
Can anyone please help?
Also how can I know what http status code was returned?

Resources