iPhone and ASIHTTPRequest - Unable to start HTTP connection - iphone

I am using the ASIHTTPRequest class in order to communicate with a web service and get a response. This is how I send a request to the server
NSString *str = [NSString stringWithFormat:#"%#verifyLogin.json", serverUrl];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request addRequestHeader:#"Content-Type" value:#"text/x-gwt-rpc; charset=utf-8"];
NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys:emailId, #"username", pwd, #"password", nil];
[request appendPostData: [[data JSONFragment] dataUsingEncoding: NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setDidFinishSelector: #selector(gotLoginResponse:)];
[request setDidFailSelector: #selector(loginRequestFailed:)];
[networkQueue addOperation: request];
[networkQueue go];
The control immediately goes to the error routine and the error description and domain are
Unable to start HTTP connection and ASIHTTPRequestErrorDomain
I can get the same request to work via a desktop tool for checking HTTP requests so I know the settings are all correct.
Can someone please tell me what I am missing here while sending the request?
Thanks.

As I commented earlier;
in your first line it says
"%verifyLogin.json". Shouldn't that
be; "%#verifyLogin.json" ????

For me I forgot to add http:// as i was testing locally. But after adding http it ran successfully

Can you check the status code of the request when it fails? I recently dealt with a JSON user authentication issue with ASI-HTTP-Request where the first request would always fail with Status Code 0 and some sort of underlying network connection failure (as if it wasn't connected to the internet, but clearly was).
I was able to solve it by setting that particular request to not attempt to use a persistent connection.
So try that first!

Related

Getting Metadata from shoutcast iOS programming

Hello I am trying to parse Shoutcast radio's metadata in iOS.
After trying many submitted solutions, I end up with a piece of code that is still giving me error
Response String: ICY 404 Resource Not Found
icy-notice1:SHOUTcast Distributed Network Audio Server/Linux v1.9.8
icy-notice2:The resource requested was not found
the code im trying to parse metadata
NSURL *url = [NSURL URLWithString:#"http://relay.181.fm:8052/7.html"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"1" forHTTPHeaderField:#"icy-metadata"];
[request addValue:#"Winamp 5/3" forHTTPHeaderField:#"User-Agent"];
[request addValue:#"audio/mpeg" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response String: %#", responseString);
any ideas about problem, thanks for helping
Not all SHOUTcast servers allow access to 7.html. There are two other ways to get that data.
The XML data for SHOUTcast is generally available, but requires the server's password. You can request it using /admin.cgi?mode=viewxml&page=4.
You can also read the metadata right out of the stream. This is more cumbersome, but entirely possible, and not too difficult. See this answer for details: https://stackoverflow.com/a/4914538/362536
I found a solution for those who can't/doesn't want to read metadata from stream.
Its the easiest solution I have seen.
http://www.fvalente.org/blog/2012/03/15/shoutcast-metadata-the-easy-way/
Brad says in the post above
Not all SHOUTcast servers allow access to 7.html.
so it is better to check if the server you want to get metadata has /7.html page
the current song is also displayed on the page /played.html but it works in a web browser along with /7.html. But when i tried in fiddler2 on a windows machine i got the ICY 404 resource not found error

iPhone ASIHttpRequest - can't POST variables asynchronously

Greetings,
I'm trying to simply POST data to a url using ASIHttpRequest.
Here is my code:
__block ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
[request setPostBody:[NSMutableData dataWithData:[#"uname=Hello" dataUsingEncoding:NSUTF8StringEncoding]]];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response=[request responseString];
UIAlertView *msg=[[UIAlertView alloc] initWithTitle:#"Response" message:response delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[msg show];
[msg release];
}];
[request setFailedBlock:^{
NSError *error =[request error];
}];
[request startAsynchronous];
Basically, my url is xxx.xxx.xxx.xxx/login.php, when I dump the PHP $_POST variable, I just get an empty array - i.e. no POST parameters are sent! The rest of the PHP is tested and working fine.
I've looked through the allseeing-i.com documentation and examples and can't seem to resolve this problem.
Any insight greatly appreciated.
Many thanks in advance,
I am having the exact same problem. I am using ASIHTTPRequest and trying to set my own POST data. I have tried both [request setPostBody:] and [request appendPostData:].
When I run these lines just before I start the request, I find that both the method and the data are what I expect.
NSLog(#"%#", [request requestMethod]);
NSLog(#"%#", [[[NSString alloc] initWithBytes:[[request postBody] bytes]
length:[[request postBody] length]
encoding:NSUTF8StringEncoding] autorelease]);
When I send it to the server, however, the request is made and logged but the POST data is empty.
I have, however, gotten my code working by switching to ASIFormDataRequest.
Reading the documentation, however, suggests to me that what you and I are doing should be working, so I suspect that is a bug in ASIHTTPRequest and I will contact the author to see if this is the case.
Update
One possibility is that the code is redirecting to another URL. In that case, the post data may be dropped. If that is the case, you can try using
[request setShouldUseRFC2616RedirectBehaviour:YES];⠀⠀⠀
which will allow the request to send the post data to the redirected URL.
I believe you need to setup the callback functions for async.
-(void)requestFinished:(ASIHTTPRequest *)request{
NSLog([request responseString]);
}
edit: looking again, u had some completion block code there... never seen that before, but maybe that takes care of what i posted above

Clearing credentials from ASIHTTPRequest

I'm working on an iPhone app that uses ASIHTTPRequest to interact with a web service using NTLM authentication. And the credentials should be stored in the keychain. It logs in fine, but I'd like to have a logout button that clears the credentials from the app, and I can't get that to work.
After I click the logout button, I expect that when I return to the view that queries the server that I'll get prompted to log back in again. However, that doesn't happen and the call to the server still authenticates.
The code that makes the request looks like this:
NSString *urlString = [NSString stringWithFormat:#"http://myserver.mydomain.com/myapp/items/%#", itemGroupId];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request setShouldPresentAuthenticationDialog:YES];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json;charset=utf-8"];
[request addRequestHeader:#"content-length" value:#"0"];
[request setDelegate:self];
[request startAsynchronous];
For the logout, I've tried calling:
[ASIHTTPRequest removeCredentialsForHost:#"myserver.mydomain.com" port:0 protocol:#"http" realm:nil];
But that doesn't work. The code inside that method doesn't find the NSURLCredential that was saved so that it can remove it, even though those arguments are what I've seen get passed to saveCredentials:forHost:port:protocol:realm: in the first place.
I've also tried calling clearSession, and I've tried disabling session persistence altogether when creating the request using setUseSessionPersistence, but no luck.
I also tried using code based on this example that loops through all of the credentials in the app's keychain and removes them all:
NSURLCredentialStorage *store = [NSURLCredentialStorage sharedCredentialStorage];
for (NSURLProtectionSpace *space in [store allCredentials]) {
NSDictionary *userCredentialMap = [store credentialsForProtectionSpace:space];
for (NSString *user in userCredentialMap) {
NSURLCredential *credential = [userCredentialMap objectForKey:user];
[store removeCredential:credential forProtectionSpace:space];
}
}
That sort of works, because the next time the app is launched it'll prompt for a login again. But it doesn't prompt for another login if the app continues to run.
Are you sure using port 0 and no realm is correct?
Just to make sure I create a NSURL from my connect-url-string (the same url I use for all ASIHTTPRequest), and retrieve the host, port and protocol from that. I only have to mention the realm by hand for now.
Using this code I am able to logout successfully in my app:
// clear keychain
NSURL *url = [NSURL URLWithString:kConnectorUrlString];
[ASIHTTPRequest removeCredentialsForHost:[url host] port:[[url port] intValue] protocol:[url scheme] realm:kConnectorRealm];
My app prompts me again when I let my app continue to run.
I am using the same arguments who get passed to saveCredentials too.

graph.facebook.com and FacebookConnect on iPhone: How can I remove a "like"

I'm developing an iPhone application using the Facebook Connect API. I arrived to set the "Like" on a post using the following code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/likes", discussion.postId]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[self.facebook accessToken] forKey:#"access_token"];
[request setDelegate:self];
[request startAsynchronous];
It generates the following call:
HTTP POST https://graph.facebook.com/147512198609691_148877991806445/likes
But I'm not able to do the inverse operation "Unlike" (removing the like
from the post).
I tried the following:
HTTP POST https://graph.facebook.com/147512198609691_148877991806445/likes?access_token=....&method=delete
and also:
HTTP DELETE https://graph.facebook.com/147512198609691_148877991806445/likes?access_token=....
But those are not working, probably I'm using a wrong command.
[request setPostValue:#"DELETE" forKey:#"method"];

API image file upload iPhone to Ruby on Rails

I am a backend Rails developer of an API that services several iPhone clients. I'm not an iPhone dev.
I have a need to accept binary data (several image files in this case) from the client via a POST request to the API.
To get the file content (file metadata other than image type is not relevant here), what tools might be used by the iPhone developer? I've found ObjectiveResource (used by iPhone on Rails) and ASIHTTPRequest. In the pages I found for those, there's no indication of what form the uploaded file will have when the controller action is executed. Will it be a Ruby File object or Tempfile object? I don't control the iPhone code development, there are some cross-cultural communication difficulties there, and they haven't used those suggestions so far. If I can submit better information to them, I might be getting better data back.
The backend app is currently running Rails 2.3.10, and will soon (in the next few weeks) likely be converted into Rails 3.
Thanks,
Craig
ObjectiveResource does not natively support file uploads. Try instead using ASIHTTPRequest with this snippet:
NSURL *url = [NSURL URLWithString:#"http://localhost:3000/file"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Sample" forKey:#"name"];
[request setFile:... forKey:#"file"];
[request startSynchronous];
For more details, see the example page here (sending data).
The post will be encoded as a standard multipart form post (just like if it came from an HTML form). If you are using paperclip to store your uploads, the magic will just happen!
Use JSON over HTTP
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:urlStr]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [jsonMessageStr length]];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection =
[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];