Error in accessing google reader's Endpoints API - iphone

I am trying to implement google reader in iPhone APP and so far I have successfully received the sid and auth. The problem arises when I try to call the Endpoints API with GET.. Here's the code:
ASIHTTPRequest *request = [self requestForAPIEndpoint:#"https://www.google.com/reader/api/0/subscription/list?output=json"];
[request setDelegate:self];
[request startAsynchronous];
- (ASIHTTPRequest *) requestForAPIEndpoint: (NSString *) apiEndpoint
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString: apiEndpoint]];
[request addRequestHeader: #"User-Agent" value: #"YourClient"];
[request addRequestHeader: #"Cookie" value: signature];
NSLog(#"Sig = %#",signature);
[request addRequestHeader: #"Authorization" value: autho];
return request.
}
The autho and signature are correctly set. However every-time I get callback in - (void)requestFailed:(ASIHTTPRequest *)request method. What is that I am doing wrong?? Do I need to register some where to access the API and set the user-agent to that name??
I modified the requestForAPIEndpoint method as follows then also I have the same problem.
- (ASIHTTPRequest *) requestForAPIEndpoint: (NSString *) apiEndpoint
{
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:signature forKey:NSHTTPCookieValue];
[properties setValue:#"SID" forKey:NSHTTPCookieName];
[properties setValue:#".google.com" forKey:NSHTTPCookieDomain];
[properties setValue:#"1600000000" forKey:NSHTTPCookieExpires];
[properties setValue:#"/" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString: apiEndpoint]];
[request setUseCookiePersistence:NO];
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
[request addRequestHeader: #"User-Agent" value: #"YourClient"];
[request addRequestHeader: #"Authorization" value: autho];
return request;
}

You don't need to provide the SID cookie if you are using ClientLogin (via the Authorization header). See http://code.google.com/p/google-reader-api/wiki/Authentication for the supported authentication schemes.
Additionally, the Authorization header should be formatted as GoogleLogin auth=<auth token> where <auth token> is the Auth value from the ClientLogin response.

Related

post request json parsing

question_id = 28, value = 'yes', null for now
then function will get
{
question_id = 22,
value = 'yes',
array = (9=>1, 28 => 0)
}
9 is id 1 for yes and 0 for no.
the array stores all previous questions and answers
and display the result if there is no question.
How do i implement/post/ this using two action buttons yes and no??
You can use the following code snippet, as described in this article:
Here, I simple describe how can use of POST method.
1. Set post string with actual username and password.
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
You need to send the actual length of your data. Calculate the length
of the post string.
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest
object and initialize it.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
Set the Url for which your going to send the data to that request.
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.abcde.com/xyz/login.aspx"]]];
Now, set HTTP method (POST or GET). Write this lines as it is in
your code.
[request setHTTPMethod:#"POST"];
Set HTTP header field with length of the post data.
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
Also set the Encoded value for HTTP header Field.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
Set the HTTPBody of the urlrequest with postData.
[request setHTTPBody:postData];
4. Now, create URLConnection object. Initialize it with the URLRequest.
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
It returns the initialized url connection and begins to load the data
for the url request. You can check that whether you URL connection
is done properly or not using just if/else statement as below.
if(conn)
{
NSLog(#”Connection Successful”)
}
else
{
NSLog(#”Connection could not be made”);
}
5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference.
Delegate methods are as below.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
Above method is used to receive the data which we get using post
method.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
This method , you can use to receive the error report in case of
connection is not made to server.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above method is used to process the data after connection has made
successfully.
Also Refer This and This documentation for POST method.
And here is best example with source code of HTTPPost Method.
EDITED:
-(void) buttonPressed:(id) sender
{
NSURL *url = [NSURL URLWithString:#"URL"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setShouldStreamPostDataFromDisk:YES];
[request setDidFinishSelector:#selector(uploadFinished:)];
[request setDidFailSelector:#selector(uploadFail:)];
[request setTimeOutSeconds:300];
[request setPostValue:#"Login" forKey:#"action"];
[request setPostValue:Yourvalue1 forKey:#"key1"];
[request setPostValue:Yourvalue2 forKey:#"key2"];
.
.
.
request.delegate = self;
[self.sendLoader startAnimating];
[request startAsynchronous];
}
#pragma Mark -
#pragma Mark - ASIHTTPRequest Methods
- (void) uploadFinished:(ASIHTTPRequest *)request
{
NSString *str = [request responseString];// convert it as JSON also.
}
- (void) uploadFail:(ASIHTTPRequest *)request
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Connection failed !!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show];
}

Can not get tweets on my twitter account using third party API in Iphone app

-(IBAction)btnPostclick
{NSURL *url = [NSURL URLWithString:#"http://yfrog.com/api/uploadAndPost"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
if (IMG)
{
if([galleryImageView.image description] == NULL)
{
[request setData:UIImageJPEGRepresentation([UIImage imageNamed:#"logo.png"], 0.8) forKey:#"media"];
}
else
{
[request setData:UIImageJPEGRepresentation(galleryImageView.image, 0.8) forKey:#"media"];
}
}
else
{
[request setData:UIImageJPEGRepresentation([UIImage imageNamed:#"logo.png"], 0.8) forKey:#"media"];
}
[request setPostValue:userdata.twitterUserName forKey:#"username"];
[request setPostValue:userdata.twitterPassword forKey:#"password"];
[request setPostValue:comm forKey:#"message"];
[request startAsynchronous];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestFailed:)];}
I m using yfrog API to share image and tweets.
I call the above API using ASIFormDataRequest. I have set my twitter username & password in request. The request is called asynchronously.
When reponse arrives -(void)requestDone:(ASIHTTPRequest *)request method get called automatically.
I get successful response in
-(void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
NSLog(#"Response -> %#",response);
}
But it does not send tweets on my twitter account.
Can anyone solve this issue ?
Base SDK for app is: iOS 4.3
Deployment Target for app is: 3.1.3
Thanks in advance.

ASIHTTPRequest appendPostData not working

I want to send String Data to a php server using the ASIHTTPRequest appendPostData method but its not working.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[#"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startAsynchronous];
I tried some modifications on the request itself like:
[request setRequestMethod:#"POST"];
[request buildPostBody];
but also this does not work.
When i use the
[request addPostValue:#"Ben" forKey:#"names"];
syntax it does work.
Anybody has an idea whats wrong here?!
I usually use this:
- (void)performPostRequestWithString:(NSString *)string stringDictionary:(NSDictionary *)stringDictionary dataDictionary:(NSDictionary *)dataDictionary delegate:(id)requestDelegate requestSelector:(SEL)requestSelector errorSelector:(SEL)errorSelector {
//localCopy = self;
self.delegate = requestDelegate;
self.callback = requestSelector;
self.errorCallback = errorSelector;
NSURL *url = [NSURL URLWithString:string];
postRequest = [[ASIFormDataRequest alloc] initWithURL:url];
[postRequest setDelegate:self];
[postRequest setRequestMethod:#"POST"];
if (stringDictionary)
for (NSString *key in [stringDictionary allKeys])
[postRequest setPostValue:[stringDictionary objectForKey:key] forKey:key];
if (dataDictionary)
for (NSString *key in [dataDictionary allKeys])
[postRequest setData:[dataDictionary objectForKey:key] forKey:key];
//NSLog(#"request url = %#", [postRequest.url absoluteString]);
[postRequest startAsynchronous];
}
Parameters:
(NSString *)string - url string, where to post your request;
(NSDictionary *)stringDictionary - dictionary, which contains all the text information (such as name, id etc.);
(NSDictionary *)dataDictionary - dictionary, which contains all data information (such as photos, files, etc.);
(id)requestDelegate - delegate to perform selectors below;
(SEL)requestSelector - selector, which will be executed while successfully request;
(SEL)errorSelector - selector, which will be executed, while error occurred.
P.S. Selectors will be used in the ASIHTTPRequest Delegate implementation

Sending JSON Request to server?

I have following JSON for sending request on server
{
"name":"Home",
"latitude":"45.5037078163837",
"longitude":"-122.622699737549",
"radius":"240"
}
and URL of for request is
URL: https://api.geoloqi.com/1/place/create
I am making request like this,
NSString *urlString= #"https://api.geoloqi.com/1/place/create ";
NSURL* url = [[NSURL alloc] initWithString:urlString];
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\,\"radius\":\"500\ }";
jsonRequest = [self JSONString:jsonRequest];
NSData* requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [requestData length]];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
[url release];
[requestData release];
[requestDataLengthString release];
NSURLConnection *m_URLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
What is wrong with this request ?
Your JSON string seems to be missing 2 quotes after the longitude and radius values:
Change
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\,\"radius\":\"500\ }";
To this
NSString *jsonRequest = #"{\"name\":\"veer\",\"latitude\":\"45.5037078163837\",\"longitude\":\"-122.622699737549\",\"radius\":\"500\" }";
It is not clear from your question what is your issue with that.
Anyway, are you doing also:
[m_URLConnection start];
after creating the connection?
Alternatively, you could create the connection using
[– initWithRequest:delegate:startImmediately:][1]
which allows you to specify that the loading of data shall start immediately.
Also consider using [+sendAsynchronousRequest:queue:completionHandler:][2] as a convenience constructor for your connection.
The Webservice URL you are trying to hit is seem to be using SSL. You may need to put access token in request header in order to get the proper response from web service.
Please see the link for authentication:
https://developers.geoloqi.com/api/authentication

OAuthConsumer and Twitpic

I'm trying to post images to TwitPic using OAuthConsumer. I keep receiving a 401 "Could not authenticate you (header rejected by twitter)." error.
I am also making use of the Twitter+OAuth library to handle the login and posting regular tweets, and then saving the token and token secret for using with TwitPic.
This is the code I am using the construct the request:
NSURL *twitpicUrl = [NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"];
NSString* realm = #"http://api.twitter.com/";
OAToken* oaToken = [[OAToken alloc] initWithKey:savedToken secret:savedTokenSecret];
OAConsumer* oaConsumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL:twitpicUrl consumer:oaConsumer
token:oaToken realm:realm signatureProvider:nil] autorelease];
[request prepare];
[request setHTTPMethod:#"POST"];
[request setValue:#"https://api.twitter.com/1/account/verify_credentials.json" forHTTPHeaderField:#"X-Auth-Service-Provider"];
NSString* authorizeHeader = [request valueForHTTPHeaderField:#"Authorization"];
[request setValue:authorizeHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
And if I print out my headers, this is what I get (excluding the unused Authorization header):
"X-Auth-Service-Provider" = "https://api.twitter.com/1/account/verify_credentials.json";
"X-Verify-Credentials-Authorization" = "OAuth realm=\"http%3A%2F%2Fapi.twitter.com%2F\", oauth_consumer_key=\"JOvwW7mtZUjRXZRInkQI7w\", oauth_token=\"293217559-pD0HL0oE6TZSkU35mPnc7kia325oPDgMfQMTVArK\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"ctmCK35JFwx8qs8lQj0AYB6sUr4%3D\", oauth_timestamp=\"1304580843\", oauth_nonce=\"7EBE3EB0-641A-40EA-A57C-8D071B5E647F\", oauth_version=\"1.0\"";
The error I receive is:
Error: The operation couldn’t be completed. (NSURLErrorDomain error -1012.)
{"errors":[{"code":401,"message":"Could not authenticate you (header rejected by twitter)."}]}
I have excluded some detail here, specifically appending the post data, mainly because I don't think it's relevant to the error. If you think otherwise let me know and I'll update the question.
Can anyone help?
Update: Here is the code that I am now using successfully
In header:
#define kVerifyCredentialsUrl #"https://api.twitter.com/1/account/verify_credentials.json"
#define kTwitPicUrl #"http://api.twitpic.com/2/upload.json"
Implementation:
//prepare the verify credentials header
NSURL* serviceUrl = [NSURL URLWithString:kVerifyCredentialsUrl];
NSString* realm = #"http://api.twitter.com/";
OAToken* token = [[OAToken alloc] initWithKey:tokenKey secret:tokenSecret];
OAConsumer* consumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:serviceUrl consumer:consumer token:token realm:realm signatureProvider:nil];
[request setHTTPMethod:#"GET"];
[request prepare];
NSDictionary* headerDictionary = [request allHTTPHeaderFields];
NSString* oAuthHeader = [NSString stringWithString:[headerDictionary valueForKey:#"Authorization"]];
[request release];
request = nil;
//prepare the full request
serviceUrl = [NSURL URLWithString:kTwitPicUrl];
request = [[OAMutableURLRequest alloc] initWithURL:serviceUrl consumer:consumer token:token realm:realm signatureProvider:nil];
[request setHTTPMethod:#"POST"];
[request setValue:kVerifyCredentialsUrl forHTTPHeaderField:#"X-Auth-Service-Provider"];
[request setValue:oAuthHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
//add the content and start the request
UIImage* imageToUpload = [UIImage imageNamed:#"test.png"];
NSData *data = UIImagePNGRepresentation(imageToUpload);
ASIFormDataRequest *asiRequest = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:kTwitPicUrl]] autorelease];
[asiRequest addRequestHeader:#"X-Auth-Service-Provider" value:kVerifyCredentialsUrl];
[asiRequest addRequestHeader:#"X-Verify-Credentials-Authorization" value:oAuthHeader];
[asiRequest setPostValue:#"Message here" forKey:#"message"];
[asiRequest setPostValue:kTwitPicAPIKey forKey:#"key"];
[asiRequest setData:data forKey:#"media"];
[asiRequest setDidFinishSelector:#selector(requestDone:)];
[asiRequest setDidFailSelector:#selector(requestWentWrong:)];
[asiRequest setDelegate:self];
[asiRequest startAsynchronous];
Try this :
NSURL *serviceURL = [NSURL URLWithString:#"https://api.twitter.com/1/account/verify_credentials.json"];
OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:serviceURL
consumer:consumer_
token:accessToken_
realm:#"http://api.twitter.com/"
signatureProvider:nil];
[oRequest setHTTPMethod:#"GET"];
[oRequest prepare];
NSDictionary * headerDict = [oRequest allHTTPHeaderFields];
NSString * oauthHeader = [NSString stringWithString:[headerDict valueForKey:#"Authorization"]];
[oRequest release];
// Prepare the POST request
oRequest = nil;
serviceURL = nil;
serviceURL = [NSURL URLWithString:#"http://api.twitpic.com/2/upload.json"];
oRequest = [[OAMutableURLRequest alloc] initWithURL:serviceURL
consumer:consumer_
token:accessToken_
realm:#"http://api.twitter.com/"
signatureProvider:nil];
[oRequest setHTTPMethod:#"POST"];
[oRequest setValue:#"https://api.twitter.com/1/account/verify_credentials.json" forHTTPHeaderField:#"X-Auth-Service-Provider"];
[oRequest setValue:oauthHeader forHTTPHeaderField:#"X-Verify-Credentials-Authorization"];
You should also make this change in OAMutableURLRequest.m at the end of the method - (void)prepare:
NSString *oauthHeader = [NSString stringWithFormat:#"OAuth realm=\"%#\", oauth_consumer_key=\"%#\", %#oauth_signature_method=\"%#\", oauth_signature=\"%#\", oauth_timestamp=\"%#\", oauth_nonce=\"%#\", oauth_version=\"1.0\"%#",
[realm URLEncodedString],
[consumer.key URLEncodedString],
oauthToken,
[[signatureProvider name] URLEncodedString],
[signature URLEncodedString],
timestamp,
nonce,
extraParameters];
if(![self valueForHTTPHeaderField:#"X-Verify-Credentials-Authorization"])
[self setValue:oauthHeader forHTTPHeaderField:#"Authorization"];
It may also be a problem with twitter right now.
My code using OAMutableURLRequest like yours, has been working fine for ages, and today I keep getting the 401 error code. Searching twitter you will find more people having this problem recently.
This is what you can read now in the api status page:
We are currently experiencing elevated
error rates. There may be intermittent
issues loading twitter.com and Twitter
clients. We are aware of the problem
and taking action. Thanks for your
patience!
Twitter API Status