iPhone API for Accessing Amazon S3 REST API - iphone

Does anyone have any suggestions for GETing from or POSTing to Amazon S3 services using their REST API via the iPhone. It does not look like it is possible but I may be reading the docs wrong.
Thank you in advance for your help!
L.

In a general case I'd recommend to use ASIHttpRequest, it has a lot of built-in functionality (REST compatible too) and a lot of things, making life easier than with NSURLConnection.
It also has S3 support out of box.

You should be able to use the NSURLRequest stuff to do what you want.
NSMutableData* _data = nil;
- (IBAction) doIt:(id)sender {
NSURL* url = [NSURL URLWithString: #"http://theurl.com/"];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: url];
NSURLConnection* con = [NSURLConnection connectionWithRequest: req delegate: self];
NSData* body = [#"body of request" dataUsingEncoding: NSUTF8StringEncoding];
_data = [NSMutableData new];
[req setHTTPMethod: #"POST"];
[req setHTTPBody: body];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_data appendData: data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* result = [[[NSString alloc] initWithData: _data encoding: NSUTF8StringEncoding] autorelease];
// process your result here
NSLog(#"got result: %#", result);
}
This doesn't have any error checking in it and the _data variable should be stored in an instance variable, but the general idea should work for you. You will probably also need to set some request headers to tell the server what encoding the body data is in and so on.

Related

HTTP-connection with credentials to get HTML document

I would like to download an HTML documents(s) to parse the content. The server asks before entering this site to put in my user credentials. In Java I arrived with a basic authentication in an asynchronous task like this (JSoup):
String base64login = new String(Base64.encodeBase64(loginDaten.getBytes()));
Document parsableDoc = Jsoup.connect(myUrl).header("Authorization","Basic"+base64login)
.timeout(3000)
.get();
but in Objective-C it doesn't work so simple as I thought. Here I want to save the website in an NSData-Object or something similar (for example NSString). Got any ideas to solve this as simple as possible? (I'm such a pro in this sector as you can see…)
You can do this using the NSURLConnection class ad NSMutableURLRequest. The idea is that you let the NSMutableURLRequest know what kind of auth method you want to use, and the credentials (login/password).
The following code should do it. (You will need the NSdata category for base64Encoding in this link http://cocoadev.com/wiki/BaseSixtyFour )
self.receivedData = [[NSMutableData alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"login",#"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self.receivedData length] >0)
NSString *result = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];
NSLog(#"The HTML String Is : %#", result);
{

iPhone : How to fetch data from web service where web service uses "POST" method for JSON?

I want to fetch data from web service using JSON in my app.
Web service is developed in C# and it uses POST method to pass data.
I found one example but its useful only for GET method?
So How can I fetch JSON data where web service uses POST method?
And I also want to send data to web service. How can I do that ?
I'm sending POST request in following way (sending xml with some parameters).
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
NSURL *url = [NSURL URLWithString:#"https://www.site.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[message release];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
To collect data you should implement method:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
where you should save received data.
In method:
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
you can parse that data with some JSON-parser.
Hope, that will help you. If you'll have questions about this code ask them in comments.

How to post a parameters to server api using HTTP POST method in iphone

i have application in which i have a web server api .this is my api
http://192.168.0.68:91/JourneyMapperAPI?RequestType=[<EntityKey>]&Command=[GET|SET|NEW]&Token=[token]&param...n=value..n
RequestType in the query string expects an entity name requested which could be any of the database tables.
Command, in the query string should specify the operation which needs to be performed on the specified request type which could be GET SET or NEW or any other entity specific command.
For eg. i have a register form which allows the user to register.
RequestType for register form is register so the api request on the submit button click of register form would be
http://192.168.0.68:91/JourneyMapperAPI?RequestType=Register&Command=NEW&firstname=rocky&lastname=singh&Username=rocky14&Password=[password]&Email=[email];
How to post this request to server api using http post method with all these parameters and values in it so that the values will be saved in the sever table named register .Please help me in solving this problem.thanks
You can use the below function for posting data to web-server.
-(void)callCommentWebService:(NSString *)pstrCommentXML{
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<getImageComment xmlns=\"http://tempuri.org/\">"
"<Commentsxml>%#</Commentsxml>"
"</getImageComment>"
"</soap:Body>"
"</soap:Envelope>", pstrCommentXML
];
//Create URL Request
NSURL *url = [NSURL URLWithString: #"http://www.website.com/website/WebService.asmx?op=getImageComment"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
//Populate Headers
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [[NSMutableData data] retain];
}
}
Here,
url = you server web-service path
pstrCommentXML = you XML file whose format defined for upload
Then you can use simple delegate methods for getting response from server.
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response
{
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data
{
[webData appendData:data];
}
- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
}
Hope you got the point.
The easiest way IMHO would be to uses ASIHTTPRequest, or it subclass ASIFormDataRequest.
This let you easily upload text and data via POST as if it would be filling a web form — hence it name.

iPhone Objective-C: combining methods together

I'm a complete noob at objective-C, so this might be a very silly question to a lot of you.
Currently, I have a view with a 'SignIn' button, which when clicked, activates a sigupUp IBAction that I have defined below. Basically, this method needs to make a JSON call and get back some data about the user.
So, right now, my code looks something like this:
-(IBAction)signIn:(id)sender{
//run registration API call
//establish connection
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.apicallhere.com/api/auth"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
responseData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{[responseData setLength:0];}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{[responseData appendData:data];}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{/*NSLog(#"%#",error);*/}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *response=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
....code carries on from here.
}
As you can see, the problem with my code is that even though it is initiated via the 'SignUp' method, it finishes with the 'connectionDidFinishLoading' method. I want to have all this code in a single method. Not 2 separate ones, as I want to be able to return a boolean verifying if the connection was successful or not.
If someone could please tell me how to code up this procedure into a single method, I would really appreciate it.
If you really want the code all in one method, you're talking about potentially blocking all of the UI and so forth on a synchronous HTTP request method and response call.
The method to put this all "inline" is sendSynchronousRequest:returningResponse:error on NSURLConnection
[NSURLConnection sendSynchronousRequest:returningResponse:error:]
i.e.
NSError *error;
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
... do something with the NSURLResponse to enjoy with your data appropriately...
I would personally encourage you to look at an alternative for most of this sort of thing towards the asynchronous methods.

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];
}