ASIHTTPRequest only works when i hardcode the strings - iphone

I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.
Code that works. Server returns a 200 responce code.
//NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",monograph.uri];
NSURL *url = [NSURL URLWithString:#"http://www.server.com/api/monograph/com/3894.json"];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:appDelegate.key];
[request setPassword:appDelegate.secret];
[request setDelegate:self];
[request startAsynchronous];
Code that fails. Server returns 204 response code for this:
NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",monograph.uri];
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:appDelegate.key];
[request setPassword:appDelegate.secret];
[request setDelegate:self];
[request startAsynchronous];
When i NSLog urlStr it contains:
http://www.server.com/api/monograph/com/3894.json
What am i missing? There must be something to explain it -.-
Regards,
Code
EDIT
checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.

Have you checked whether the NSURL object you get from the string variable is not nil? That could help you home in on the location of the problem.
Also, you might try escaping the string variable, just incase something funny is getting in with the stringWithFormat call.

Cut all the new lines/spaces from the string, this is one possible reason. And sometimes the log doesn't show you the new lines.
try
NSString * s = [monograph.uri stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString * urlStr = [NSString stringWithFormat:#"http://www.server.com/%#",s];

Related

ASIHTTPRequest setPostValue iPhone

I'm accessing a PHP script on a server.
The request URL is like this:
example.com/cgi-bin/getEvent.cgi?EID=19573
When I put in the request via a browser, I get back my expected results.
However when I use the ASIHTTP Form request, I'm getting back a result
like the EID isn't being passed via HTTP.
NSString *eventID = #"19573";
NSString * const EVENT_URL = #"http://example.com/cgi-bin/getEvent.cgi";
-(void)callWebservice
{
NSURL *url = [NSURL URLWithString:EVENT_URL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:eventID forKey:#"EID"];
[request setNumberOfTimesToRetryOnTimeout:2];
[request setDelegate:self];
[request startAsynchronous];
}
Anyone know of a method to see the full URL being requested?
Or have any clue why this wouldn't be working?
Thanks in advance.
My guess is that your PHP script is expecting the parameter to be sent on the query string (i.e. as a GET request) rather than as a POST parameter.
If that's the case, you can fix it be sending your request as follows:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?EID=%#",EVENT_URL,eventID]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

Objective-C and Preemptive Authentication

I am trying to get data from WebService for my Ipad App.
To do that, I am using a NSURLConnection with NSMutableURLRequest.
Web Services are published on Apache-Coyote 1.1 with Preemptive Basic Authentication, but I don't know how to send my credentials from Objective-C.
Anybody knows how can I set my user/password in Objective-C to log my clients with the Apache premptive authentication system?
Thank you.
EDIT:
In order to set the creds yourself, you'll need to be able to base64 encode the username and password and set the appropriate header. Matt Gallagher, from Cocoa With Love, has a great post on how to add a category to NSData to easily do this.
NSString* username = #"username";
NSString* password = #"password";
NSString* encodedUsername = [[username dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString* encodedPassword = [[password dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSURL* url = [NSURL URLWithString:#"http://yourUrl.com/"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
NSString* headerValue = [NSString stringWithFormat:#"Basic %#:%#", encodedUsername, encodedPassowrd];
[request addValue:#"Authorization" forHTTPHeaderField:headerValue];
[NSURLConnection connectionWithRequest:request delegate:self];
As with all use of credentials, please make sure you are doing this all over HTTPS because these credentials are essentially being passed in clear text.
Consider using the ASIHTTPRequest framework, which makes preemptive Basic authentication requests simple:
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic]; /** preemptively present credentials **/
[request setUsername:#"username"];
[request setPassword:#"password"];
[request startSynchronous];
NSError *error = [request error];
if (!error)
NSString *response = [request responseString];
And, yes, you definitely want to do Basic authentication over SSL (i.e. via some https://... URL).

Objective-C and ASIHTTPRequest - response string problems

I'm using the ASIHTTPRequest package to send some data from the iPhone to my server and then when saved on server I recieve a response (a string) containing a url that I want to load in a webview. In theory this should be simple, but in reality I can't get this work at all. Seems to be some problems with encoding of the string I guess. If I NSLog out the response it seems to be totally fine, but it just refuses to load in the webview.
This is my request (been playing around with compression and encoding):
NSURL *url = [NSURL URLWithString:#"xxx"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setFile:imageData forKey:#"photo"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[request setAllowCompressedResponse:NO];
[request setDefaultResponseEncoding:NSUTF8StringEncoding];//NSISOLatin1StringEncoding
[request start];
And this is my responder:
- (void)requestDone:(ASIHTTPRequest *)request{
NSString *response = [request.responseString];
NSLog(#"web content: %#", response);
[webView loadSite:response];
}
The NSLog seems fine, but site just won't load. Tried sending an NSString variable like NSString *temp = #"http://www.google.se"; to the loadSite function and that works fine, so the problem is not with the loading itself.
Would greatly appriciate any pointers or help in the obj-c jungle :)
/f
Try to do the following:
NSString *response = [[request responseString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
It will trim all whitespaces and newlines.
so turns out that a response is automatically ended with a \n (new linebreak). this didn't show up when logging the variable, neither when writing it to a textfield but when converting it to a urlobject and logging that i found it. debugging once again pays off ;)
woups, my responder is of course:
- (void)requestDone:(ASIHTTPRequest *)request{
NSString *response = [request responseString];
NSLog(#"web content: %#", response);
[webView loadSite:response];
}

iPhone NSString convert to readable text

I have a piece of NSString that will read "Test & Test" or with "
Is there any way without searching and replacing to make that display as "&" or """ ??
Can you try this ?
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.mypage.com/content.html"]]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse* authResponse;
NSError* authError;
NSData * authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&authResponse error:&authError];
NSString *authResponseBody = [[NSString alloc] initWithData:authData encoding:NSUTF8StringEncoding];
NSLog(#" Nice Result: %#", authResponseBody);
Adrian
CFXMLCreateStringByUnescapingEntities should do it. Thanks to the magic of toll free bridging you can just use your NSString.
The html string you read is bad formated.
Try to read as UTF-8 or any other formatting in order to get the correct text from the html you're reading.
Can you actually post the code where you read the NSString from the HTML content ?