In my ipad project i am using ASIHttpRequest to handle my webservice calls. I am also doing cookie management. My webservice calls are worked fine until i have changed my service cookies all into Secure one.
How to manage Secure cookie with ASIHTTPRequest?
Thanks!
According to the docs:
You can turn off useCookiePersistence, and manage the set of cookies for a particular request manually.
//Create a cookie
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:[#"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
[properties setValue:#"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
[properties setValue:#".allseeing-i.com" forKey:NSHTTPCookieDomain];
[properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
[properties setValue:#"/asi-http-request/tests" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
//This url will return the value of the 'ASIHTTPRequestTestCookie' cookie
url = [NSURL URLWithString:#"https://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];
request = [ASIHTTPRequest requestWithURL:url];
[request setUseCookiePersistence:NO];
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
[request startSynchronous];
//Should be: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie'
NSLog(#"%#",[request responseString]);
To make the cookie secure, just add this to the properties dictionary:
[properties setValue:#"TRUE" forKey:NSHTTPCookieSecure];
Just remember, secure cookies will only be used with HTTPS requests.
Related
I have run into a little problem. I am connecting to a webservice that use Basic authentication and now I want the user to either: be able to log out, or that each time the request is made a new authentication is made. Right now the authentication seems to be cached. How do I do this?
I tried to append # at the end, but that did not seem to do the trick. The URL has the following format:
www.example.org/mywebservice/data
NSURL* url = [NSURL URLWithString: #"www.example.org/mywebservice/data"];
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection* newConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.myConnection = newConnection;
[request release];
[newConnection release];
I think you want to clear the cache of the previous requests and every time want to do new request at login. So for that just put below code before doing request for login
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
[[NSURLCache sharedURLCache] removeAllCachedResponses];
May help you
Happy Coding :)
I got it to work. I changed NSURLCredentialPersistenceSession to NSURLCredentialPersistenceNone.
NSURLCredential *cred = [[[NSURLCredential alloc] initWithUser:user.username password:user.password
persistence:NSURLCredentialPersistenceNone] autorelease];
Have you tried clearing the Authentication header in your NSURLRequest?
[urlRequest setValue:#"" forHTTPHeaderField:#"Authorization"];
I'm doing an app which retrieves user info, and it does that using a GET request, but I don't know how could I make one. Already tried ASIHTTPRequest with this code:
NSURL *url = [NSURL URLWithString:#"http://forrst.com/api/v2/users/info"];
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:#"1" forKey:#"id"];
[request setRequestMethod:#"GET"];
// Initiate the WebService request
[request setDelegate:self];
[request startAsynchronous];
But I get this response from forrst:
2011-06-05 16:59:32.189 Forrsty[4335:207] {"resp":{"error":"you must pass either id or username"},"stat":"fail","in":0.0557,"authed":false,"authed_as":false,"env":"prod"}
Which I understand I'm not doing the GET request ok, so how I would do it? Thanks :)
A Get Parameter ?
So why don't you try "http://forrst.com/api/v2/users/info?id=1" ?
[ NSString stringWithFormat:#"http://forrst.com/api/v2/users/info?id=%d", 1 ];
By the way, take a look at this librayry : http://allseeing-i.com/ASIHTTPRequest/
Good luck !
I'm rather new to trying to figure out how JSON and the DropBox API function with the iphone SDK that DB has release for the iPhone. I understand how both technologies work in general and that you have to build a dictionary into a request and get another dictionary back, but I can't find a solid example of how to do anything specifically enough online in Objective C.
I just need one example of how to retrieve for instance the user's profile information by creating a JSON request to fetch info from the drop-box server.
I've been able to log the user in and linking the device using the consumer key and consumer secret but what's next I'm a little at a loss.
MANY thanks for any guidance or examples.
To send your data
Example for POST methods:
url = #"https://api.dropbox.com/<version>/account/"
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:value forKey:#"callback"];
Example for GET methods (URL queries):
NSString *urlString = [[[NSString alloc] initWithString:#"https://api.dropbox.com/<version>/account/info
"] autorelease];
urlString = [urlString stringByAppendingFormat:#"?callback=whatever&status_in_response=something"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDidFinishForThreadID:)];
[request startAsynchronous];
To retrieve JSON values and convert them into Dictionary
SBJsonParser *json = [[SBJsonParser alloc] init];
NSDictionary *dict = (NSDictionary*)[json objectWithString:responseString];
You will need JSON Framework: http://code.google.com/p/json-framework/
And also ASIHTTPRequest: http://allseeing-i.com/ASIHTTPRequest/
Haven't tested it with dropbox, but should be this way.
I see the rate limit is 150/hr per IP. This'd be fine, but my application is on a mobile phone network (with shared IP addresses).
I'd like to query twitter trends, e.g. GET /trends/1/json.
This doesn't require authorization, however what if the user first authorized with my application using OAuth, then hit the JSON API?
The request is built as follows:
- (void) queryTrends:(NSString *) WOEID {
NSString *urlString = [NSString stringWithFormat:#"http://api.twitter.com/1/trends/%#.json", WOEID];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
if (theConnection) {
// Create the NSMutableData to hold the received data.
theData = [[NSMutableData data] retain];
} else {
NSLog(#"Connection failed in Query Trends");
}
//NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
}
I have no idea how I'd build this request as an authenticated one however, and haven't seen any examples to this effect online.
I've read through the twitter OAuth documentation, but I'm still puzzled as to how it should work.
I've experimented with OAuth using Ben Gottlieb's prebuild library, and calling this in my first viewDidLoad:
OAuthViewController *oAuthVC = [[OAuthViewController alloc]
initWithNibName:#"OAuthTwitterDemoViewController" bundle:[NSBundle mainBundle]];
// [self setViewController:aViewController];
[[self navigationController] pushViewController:oAuthVC animated:YES];
This should store all the keys required in the app's preferences, I just need to know how to build the GET request after authorizing!
Maybe this just isn't possible? Maybe I'll have to proxy the requests through a server side application?
Any insight would be appreciated!
Authorizing through OAuth will provide you an authorization token, which you need to pass to each request you make later on.
Refer to Twitter docs, read about how authorization works.
Okay, after a lot of searching I've managed to figure how to construct a request to the JSON API programmatically in Xcode.
Firstly, you need to use the OAuth demo code to authenticate and authorize your application.
Then, you'll be retrieving the key by doing: [prefs stringForKey:#"authData"] - if this doesn't exist, you haven't been OAuth'd properly.
I had to reverse engineer this by looking through the code of the OAuth library, and while it's easy to use the library for stuff like sending a status update, it doesn't allow you to retrieve trends...:
#import "OAMutableURLRequest.h"
#import "MGTwitterHTTPURLConnection.h"
NSMutableString *dataString;
// Using OAuth:
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:#"YOURCONSUMERKEY"
secret:#"YOURCONSUMERSECRET"];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *authData = [prefs stringForKey:#"authData"];
// [_engine
OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://stream.twitter.com/1/statuses/filter.json"]
consumer:consumer
token: (authData) ? [[OAToken alloc] initWithHTTPResponseBody:authData] : nil
realm: nil
signatureProvider:nil] autorelease];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [httpBody dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:#"Trendy" forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:#"1.0" forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:#"http://www.inisdesign.com" forHTTPHeaderField:#"X-Twitter-Client-URL"];
// Set the request body if this is a POST request.
[theRequest prepare];
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:MGTwitterFollowedTimelineRequest // Wrong type
responseType:MGTwitterStatuses]; // as above - doesnt seem to matter
if (!connection) {
return;
} else {
// [_connections setObject:connection forKey:[connection identifier]];
// [connection release];
dataString = [[NSMutableData data] retain];
[connection start];
}
}
The rest is implemented as a standard URL connection with didReceiveData methods etc..
I haven't verified this is alleviating my rate limiting problems, but hey.. It's a start if anybody has similar problems.
I have a web site hosted on IIS with windows authentication. I am trying to access it in one of my iPhone web application. Presently i am using this code, but it is not working.
NSString *authString = [[[NSString stringWithFormat:#"%#:%#", #"myusername", #"mypassword"]dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];
authString = [NSString stringWithFormat: #"Basic %#", authString];
**[requestObj setValue:authString forHTTPHeaderField:#"Authorization"];**
my web app is hosted with windows authentication. but here i am using basic. can any one post what is the correct http header for it.
Thanks..
I think the main difference is you need to specify the domain you are authenticating against as well as the username and password. Something like this should work. I've used a synchronous request for brevity, ideally you should use an ASINetworkQueue or NSOperationQueue to perform the request.
NSString *username = #"test";
NSString *password = #"test";
NSString *domain = #"test";
NSURL *url = [NSURL URLWithString:#"http://myurl"];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setUseSessionPersistence:YES];
[request setUsername:username];
[request setPassword:password];
[request setDomain:domain];
[request start];
if ([request error]) {
if ([[request error] code] == ASIAuthenticationErrorType) {
//Authentication failed
}
} else {
NSLog([request responseString]);
}
I don't have access to a Windows server to test this, but I have tested NTLM in the past so it should work... :)
Windows authentication (NTLM) isn't as simple as basic authentication. NTLM requires more than one webrequest to negotiate the security so there isn't a static HTTP header you can send to log in.
You can use the third-party ASIHTTPRequest library to perform NTLM over HTTP authentication.
I'm not 100% sure it supports NTLM Authentication but have you investigated the connection:didReceiveAuthenticationChallenge method on the NSUrlConnection?