I'm using this small chunk of code to post in Twitter, with real credentials in place of 'mytwitterloginname' and 'mytwitterpassword' placeholders:
void _StartTwitter()
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:#"http://mytwitterloginname:mytwitterpassword#twitter.com/statuses/update.xml"]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
// The text to post
NSString *msg = #"testing";
// Set the HTTP request method
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[[NSString stringWithFormat:#"status=%#", msg]
dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response;
NSError *error;
if ([NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error] != nil)
NSLog(#"Posted to Twitter successfully.");
else
NSLog(#"Error posting to Twitter.");
}
But even my console says the post was succeful it still doesn't happen.
Can anyone help me to find what's wrong ?, thanks.
I though twitter had only O-AUTH authentication now, so you couldn't post information simply through their REST service anymore.
You may need to re-integrate with their new OAUTH service.
UPDATE:
Here is the link to the OAUTH Examples:
Twitter - OAUTH
The bummer part that I needed to do was create a WebUI view in order to go through the silly steps twitter now enforces. After doing a request to authenticate (which is bound to an app created in twitter), my session was created and from there I could do my posting of a message.
Not nearly as user friendly as the previous REST service :/
Related
I followed this tutorial and was able to authenticate successfully and got the access token, now I am struggling to understand how can I get email associated with user profile before closing webview and join back my controller.
Any suggestions? I understand that Google has SDK for this, but I don't want to go that route if my requirement is possible with the tutorial I am using.
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
//Should I need to call another HTTP to retrieve email (or) email already available part of any other response?
If I need to call another HTTP, what URL should be invoked?
Make an authenticated request to the people.get API method with the userId set to me. The person resource has an emails array and the email with type set to account is their verified email.
I need to upload video files from my app to a server. I tried doing so via [AFHTTPRequestOperationManager post:parameters:success:failure] but unfortunately kept getting request timeouts. I'm now trying something similar to Creating an Upload Task from the AF Docs.
I read on SO and the AF Docs about setSessionDidReceiveAuthenticationChallengeBlock: and tried to implement the whole upload malarky as follows:
__block ApiManager *myself = self;
// Construct the URL
NSString *strUrl = [NSString stringWithFormat:#"%#/%#", defaultUrl, [self getPathForEndpoint:endpoint]];
NSURL *URL = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
// Build a session manager
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// Set authentication handler
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
*credential = myself.credentials;
return NSURLSessionAuthChallengeUseCredential;
}];
// Create the upload task
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
[myself endpoint:endpoint returnedFailure:error];
} else {
[myself endpoint:endpoint returnedSuccess:responseObject];
}
}];
// and run with it
[uploadTask resume];
The myself.credentials object has been set previously to have the correct username and password. Whenever this request fires, I get 401 unauthorised as a response. I tried putting NSLog(#"CHALLENGE") inside the challenge block above, but it never seems to get called, so AFNetworking isn't giving me a way to supply credentials. I know that this works perfectly well on the server side because I've tested it with Postman.
How can I get AFNetworking to let me supply credentials for HTTP Basic Auth with this upload task?
I'm not sure about AFNetworking's setSessionDidReceiveAuthenticationChallengeBlock, but as long as you have an NSMutableURLRequest you may set the Authorization HTTP Header directly on the request object:
[request setValue:base64AuthorizationString forHTTPHeaderField:#"Authorization"];
Keep in mind that the value must be base64 representation of the username:password string.
Otherwise, for GET, POST, etc. requests on a session manager, you may set the credentials on the request serializer used by the session manager. See:
[AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:]
[AFHTTPRequestSerializer clearAuthorizationHeader]
I'm trying to create a synchronous REST request to an API. The API uses HTTP Basic authentication, so in addition to sending an Accept: application/json header, I need to specify the Authorization header as well with my Base64-encoded username and password pair. When I use just one header the request executes just fine (either successfully authenticating me, or specifying my content format), but when I use both headers, it seems to ignore the Authorization line and returns "HTTP Basic access denied" (presumably a 401).
So I can't for the life of me figure out whats wrong. I'm 100% sure my credentials are valid, because executing the request via REST client works just fine. I'm pretty new to Objective-C so I think perhaps there could be some kind of design pattern I'm not following. Is it valid to call setValue:forKey on an NSMutableDictionary multiple times like that? I also tried using setValue:forHTTPHeader on the request object with the same results.
Here's the code:
NSURL *url = [NSURL URLWithString:#"http://foo.com/api/v1/bar"];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *headers = [NSMutableDictionary dictionary];
NSURLResponse *urlResponse;
NSError *error;
[headers setValue:#"application/json" forKey:#"Accept"];
[headers setValue:#"Basic ..." forKey:#"Authorization"];
[request setAllHTTPHeaderFields:headers];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
The answer is to use:
[request addValue:#"Basic ..." forHTTPHeaderField:#"Authorization"];
Which adds another header into the request instance.
I try to called [ASIHTTPRequest clearSession], but the request can still return 200 status, even if use the wrong username and password.
What am I supposed to do?
ASIHTTPRequest objects store the user information in a "session" by default, you have to disable this feature on every request you create to get the behavior that you want.
From the website docs:
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:#"username"];
[request setPassword:#"password"];
[request setUseSessionPersistence:NO]; //this is the line that disables storage
More on it here.
I am using Synchronous request and passing the credentials but I am getting authentication error in response. Below is my code of request and response from server.
Request:-
NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:#"username"
password:#"paswd"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:#"http://webaddress.inc.com"
port:80
protocol:#"http"
realm:#"webaddress.inc.com"
authenticationMethod:nil];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:userCredentials
forProtectionSpace:space];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://webaddress.inc.com"]
cachePolicy:NSURLCacheStorageNotAllowed
timeoutInterval:30];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
/////////// Response
401 Authorization Required
Note: If I am sending the request with async request it is working fine as in that case
didReceiveAuthenticationChallenge is giving them the required credentials when asked for.
I am sure there might be something missing in my code.
Waiting for your valuable inputs.
Have you ever tried ASIHTTPRequest which makes easier http operations in IPhone enviroment. And It has really simple and good documentation. I used to use it inside of my projects, It was working awesome.