How to use the token given from google reader api to view unread list in objective c - objective-c

I am making a Google Reader App and so far I have been able to receive the sid, auth, and use those to get a token from http://www.google.com/reader/api/0/token?client=clientName.
My next step if I am correct is to send a GET request using this token to a url that will return me a list of unread messages.
Problem is I do not know what url to use or how to send this GET request using the ID's i have.
Can someone please show me some code that actually does this correctly in objective c.

Assuming you're using a NSURLRequest in Objective-C you can set a custom header like this:
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
autorelease];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=#%", token]
forHTTPHeaderField:#"Authorization"];
This is assuming you have two strings defined already, the URL and the token.
The URL you want is http://www.google.com/reader/atom/user/-/state/com.google/read
I've written a PHP library to interact with Google Reader's API feel free to dig around there. Specifically line 523 is relevent to this question. The library is up to date with their latest authorization changes.

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]autorelease];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=#%", token]
forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
responseStr = [[NSString alloc]initWithData:recieveData encoding:NSASCIIStringEncoding];
NSLog(#"message %#", responseStr);

Related

Server not properly receiving POST request from ASIFormDataRequest in Objective-C

I'm trying to use an ASIFormDataRequest in my iPhone application to send a video I have just recorded to a server, along with a string that I can use to ID who the video belongs to. The code for doing so is here:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];
NSString *urlString=[urlvideo path];
NSLog(#"urlString=%#",urlString);
NSString *str = [NSString stringWithFormat:#"http://www.mysite.com/videodata.php"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSData *patientData = [_patientCode dataUsingEncoding:NSUTF8StringEncoding];
[request setFile:urlString forKey:#"video"];
[request setData:patientData forKey:#"patientcode"];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startSynchronous];
NSLog(#"responseStatusCode: %i",[request responseStatusCode]);
NSLog(#"responseString: %#",[request responseString]);
[picker dismissViewControllerAnimated:YES completion:nil];
}
Everything seems to work correctly, I get back a status code of 200 and the method finishes as expected. However, nothing seems to be received by the php file on the server. I added this line to my server-side php code:
echo(count($_POST));
This returns 0, so it seems as though nothing is actually getting posted by the ASIFormDataRequest. I feel like there might be some simple step I am missing as I have never used the ASIFormDataRequest before, but any help would be greatly appreciated.
EDIT: I changed the setData:patientData to setPostValue:_patientCode and now that part of the post is getting sent correctly, so it seems as though setPostValue works but setData and setFile do not.
You should use -addData:forKey: and -addFile:forKey: instead of -setData:forKey: and -setFile:forKey:.
Other than that, check the debug output when you compile with DEBUG_FORM_DATA_REQUEST.
You should be sending a multipart/form-data request when using -addFile:forKey: and a application/x-www-form-urlencoded request when using -addPostValue:forKey:.
Does your server handle multipart/form-data requests?
I ended up finding the answer while reading something else and noticing that they did something interesting: The file I uploaded was simply going into the $_FILES array, not the $_POST array. I also changed [request setData:patientData forKey:#"patientcode"]; to [request setPostValue:_patientCode forKey:#"patientCode"]; and then that appeared in the $_POST array as I wanted so I was able to get both the string I was sending and the file I was sending in my php script.

AFNetworking Overload a Post Parameter

I am migrating from ASIHTTPRequest to AFNetworking and have run into an issue.
I am trying to hit an API with a request that overloads the post parameter. I was previously using ASIFormDataRequest for this and used this code to update 3 ids at the same time.
// ASIHTTPRequestCode
[request addPostValue:#"value1" forKey:#"id"];
[request addPostValue:#"value2" forKey:#"id"];
[request addPostValue:#"value3" forKey:#"id"];
Since AFNetworking uses an NSDictionary to store key value pairs, it doesn't seem straight forward how to do this. Any ideas?
I can't immediately see a direct way to do this with AFNetworking, but it is possible to do.
If you look at the code for AFHTTPClient requestWithMethod, you'll see this line, which is the one that sets up the request body to contain the parameters:
[request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
Basically you could pass an empty dictionary to requestWithMethod for the parameters, then it returns, call request setHTTPBody yourself, making up the query string yourself in a similar way to the way AFQueryStringFromParametersWithEncoding does it.
You can build the request this way:
NSURL *url = [NSURL URLWithString:#"http://www.mydomain.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *postValues = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"%#,%#,%#",#"value1",#"value2",#"value3"] forKey:#"id"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"/path/to/your/page.php" postValues];
I was facing a similar issue but solved it by updating the url. I added the parameters i need to send with the url and set the "parameters to nil"
so the url became something like
server\url.htm?data=param1&data=param2&data=param3
and sent nil as paramDictionary
[request setHTTPBody:[AFQueryStringFromParametersWithEncoding(nil, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];

iOS simulator getting connectionDidReceiveResponse with no Internet

I have been thinking if I should post this question, but I have tried to understand what may be happening and get no idea.
My app downloads some xml files from a server.
I have tried it with no internet connection (my router is off, wifi is off) but the simulator keeps getting a 200 http response and showing the data downloaded.
I have logged the response's status code and get 200, and the currentRequest url and the info is correct (the resource's url).
Is there any cache or something where the simulator is getting the data?
The network icon on status bar on simulator is always on.
You could try this code. It don't cache a data.
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT_REQUEST];
[request setHTTPMethod:#"GET"];
[request setAllHTTPHeaderFields:headers];
The asy way to fix this is to use the following method of NSMUtableURLRequest:
[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
The NSURLRequestReloadIgnoringLocalAndRemoteCacheData value is the most strict "don't cache anything ever!" option but if you want more specific control, have a look at the docs for the NSURLRequestCachePolicy enum for all possible options.

Getting SHOUTcast metadata on the Mac

I'm creating an application in Objective-C and I need to get the metadata from a SHOUTcast stream. I tried this:
NSURL *URL = [NSURL URLWithString:#"http://202.4.100.2:8000/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request addValue:#"1" forHTTPHeaderField:#"icy-metadata"];
[request addValue:#"Winamp 5/3" forHTTPHeaderField:#"User-Agent"];
[request addValue:#"audio/mpeg" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection connectionWithRequest:request delegate:self];
I would have to get the headers from this request in order to get the information, right? Unfortunately it keeps returning these headers:
Date = "17 Apr 2010 21:57:14 -0200";
"Max-Age" = 0;
What I'm doing wrong?
I found an answer to this question. Simply append a 7.html at the end of the URL and parse the file.
I.E.
http://38.96.148.138:7534/7.html
Fernando Valente's solution for this problem
http://www.fvalente.org/blog/2012/03/15/shoutcast-metadata-the-easy-way/
It seems that shoutcast does not follow HTTP exchange standards and its response headers and body are not separated by two newlines. NSURLConnection/NSURLResponse are unable to parse out the headers; however, connection:didReceiveResponse: is still fired, just with an empty NSURLResponse. This becomes clear if we take a look at data coming in connection:didReceiveData:. The first chunk received will contain metadata headers.

Google App Engine with ClientLogin Interface for Objective-C

I'm experiencing the same problem in this previous stackoverflow.com post.
Specifically, I seem to be able to get the "Auth" token correctly, but attempts to use it in the header when I access later pages still just return me the login page's HTML.
Following links related to this post, I've determined that you need to make a subsequent call to this URL.
A call to the URL will then give you an ACSID cookie which then needs to be passed in subsequent calls in order to maintain an authenticated state.
When requesting this cookie, I've read various posts saying you need to specify your original auth token by appending it to the query string such that:
?auth=this_is_my_token
I've also read that you should set it in the http header as described in google's documentation such that a http header name/value is:
Authorization: GoogleLogin auth=yourAuthToken
I've tried both approaches and am not seeing any cookies returned. I've used Wireshark, LiveHttpHeaders for Firefox, and simple NSLog statements trying to see if anything like this is returned.
Below is the code snippet I've been using.
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://yourapp.appspot.com/_ah/login?auth=%#", [token objectForKey:#"Auth"]]];
NSHTTPURLResponse* response;
NSError* error;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=%#", [token objectForKey:#"Auth"]] forHTTPHeaderField:#"Authorization"];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//show me all header fields
NSLog([[response allHeaderFields] description]);
//show me the response
NSLog(#"%#", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]);
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://yourapp.appspot.com/_ah/login"]];
//show me all cookies
for (NSHTTPCookie *cookie in all)
{
NSLog(#"Name: %# : Value: %#", cookie.name, cookie.value);
}
I hope you can use ClientLogin for Google App Engine code.
Adding sample code to this question because someone contacted me directly about my solution. Note that you must set the "service" parameter equal to "ah" on the initial token request.
Initial Request of Token [done synchronously] NOTE: the "service" parameter is set to "ah" and the "source" is just set to "myapp", you should use your app name.
//create request
NSString* content = [NSString stringWithFormat:#"accountType=HOSTED_OR_GOOGLE&Email=%#&Passwd=%#&service=ah&source=myapp", [loginView username].text, [loginView password].text];
NSURL* authUrl = [NSURL URLWithString:#"https://www.google.com/accounts/ClientLogin"];
NSMutableURLRequest* authRequest = [[NSMutableURLRequest alloc] initWithURL:authUrl];
[authRequest setHTTPMethod:#"POST"];
[authRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
[authRequest setHTTPBody:[content dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* authResponse;
NSError* authError;
NSData * authData = [NSURLConnection sendSynchronousRequest:authRequest returningResponse:&authResponse error:&authError];
NSString *authResponseBody = [[NSString alloc] initWithData:authData encoding:NSASCIIStringEncoding];
//loop through response body which is key=value pairs, seperated by \n. The code below is not optimal and certainly error prone.
NSArray *lines = [authResponseBody componentsSeparatedByString:#"\n"];
NSMutableDictionary* token = [NSMutableDictionary dictionary];
for (NSString* s in lines) {
NSArray* kvpair = [s componentsSeparatedByString:#"="];
if ([kvpair count]>1)
[token setObject:[kvpair objectAtIndex:1] forKey:[kvpair objectAtIndex:0]];
}
//if google returned an error in the body [google returns Error=Bad Authentication in the body. which is weird, not sure if they use status codes]
if ([token objectForKey:#"Error"]) {
//handle error
};
The next step is to get your app running on google app engine to give you the ASCID cookie. I'm not sure why there is this extra step, it seems to be an issue on google's end and probably why GAE is not currently in their listed obj-c google data api library. My tests show I have to request the cookie in order sync with GAE. Also, notice I don't do anything with the cookie. It seems just by requesting it and getting cookied, future requests will automatically contain the cookie. I'm not sure if this is an iphone thing bc my app is an iphone app but I don't fully understand what is happening with this cookie. NOTE: the use of "myapp.appspot.com".
NSURL* cookieUrl = [NSURL URLWithString:[NSString stringWithFormat:#"http://myapp.appspot.com/_ah/login?continue=http://myapp.appspot.com/&auth=%#", [token objectForKey:#"Auth"]]];
NSLog([cookieUrl description]);
NSHTTPURLResponse* cookieResponse;
NSError* cookieError;
NSMutableURLRequest *cookieRequest = [[NSMutableURLRequest alloc] initWithURL:cookieUrl];
[cookieRequest setHTTPMethod:#"GET"];
NSData* cookieData = [NSURLConnection sendSynchronousRequest:cookieRequest returningResponse:&cookieResponse error:&cookieError];
Finally, I can post json to my gae app. NOTE: the snippet below is an async request. We can handle responses by implementing didReceiveResponse, didReceiveData, didFailWIthError.
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://myapp.appspot.com/addRun?auth=%#", mytoken]];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:#"my http body";
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (!connectionResponse) {
NSLog(#"Failed to submit request");
} else {
NSLog(#"Request submitted");
}
Check out the code that does this in the official SDK. The latest SDK release even has it split into its own file.
1st - thanks for the great post it really got me started.
2nd - I have been slugging it out with my app, trying to POST to the GAE while authenticated.
This is the request is built when POSTing, once you have acquired the authtoken:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"image/png" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setValue:authtoken forHTTPHeaderField:#"auth"]; // <-- the magic
mattb
I created a few obj-c classes for implementing ClientLogin, including support for Google App Engine:
http://github.com/cameronr/GoogleAppEngineAuth
Note that Google has recently changed the way authorization failure is indicated. They used to place an Error token in the response. Now they just return a 403 (Forbidden) status. This broke my code!
Thank for this post and especially the answer from Keith but it does not works for me.
Even if it seems ok for me ... very strange.
I check this post (How do you access an authenticated Google App Engine service from a (non-web) python client?) which talk about doing the same thing in python. I test it and it works.
And the objective C code proposed by Keith is really similar to the python code.
But when I try to get the "Auth" token authData contains Error=BadAuthentication.
Some one got an idea about possibles problems ?
Using HOSTED_OR_GOOGLE is wrong, and I will explain why.
There are two kinds of accounts in the Google world. The ones you create for GMail, etc are "Google" accounts. The ones you create for Apps for Domains are "Hosted" accounts. You can use a Hosted Account email to make a Google Account, thus creating an email address that is associated with both kinds of accounts.
Your Google App Engine app can be configured to work with (1) Google Accounts or (2) Hosted Accounts for a particular domain.
Assume that we are developing an app for Google Accounts. A user enters in an email address that is associated with a Google Account and a Hosted Account. Google will use their Google Account for the login. This all works fine.
Now, if we use ClientLogin with this same email address and use HOSTED_OR_GOOGLE for the account type, login will be successful, but it will use the Hosted Account, since the Hosted Account takes precedence. As I mentioned above, you cannot use a Hosted Account for an app that expects a Google Account. So the authentication will not work.
So, when using ClientLogin to authenticate with a Google App Engine app, you need to use GOOGLE for the account type if the app is for Google Accounts, or HOSTED for the account type if the app is for a domain.