HTTP-connection with credentials to get HTML document - iphone

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);
{

Related

How to share text over to Tumblr using Xcode

I am working on an iOS application which has sharing functionality like Facebook, Twitter and Tumblr Sharing. I have done all sharing besides the Tumblr.
I've worked a lot on this. I have done a lot of googling, but found nothing on Tumblr Sharing. Here is my code currently using for sharing text over Tumblr :
- (void)shareOvertumblr:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:
[NSURL URLWithString:#"http://www.tumblr.com/api/write"]];
[request setHTTPMethod:#"POST"];
//tell the server to expect 8-bit encoded content as we're sending UTF-8 data,
//and UTF-8 is an 8-bit encoding
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
//set the content-type header to multipart MIME
[request addValue: [NSString stringWithFormat:#"multipart/form-data; boundary=%#",[NSString MIMEBoundary]] forHTTPHeaderField: #"Content-Type"];
//create a dictionary for all the fields you want to send in the POST request
NSDictionary* postData = [NSDictionary dictionaryWithObjectsAndKeys:
#"myEmailAddress", #"email",
#"password", #"password",
#"regular", #"type",
#"myTitle", #"title",
#"Hiiii How ruuu", #"body",
nil];
//here inPlace of these EmailAddress and Password using my correct emailAdress and Password
//set the body of the POST request to the multipart MIME encoded dictionary
[request setHTTPBody: [[NSString multipartMIMEStringWithDictionary: postData] dataUsingEncoding: NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
/*Here is The Category */
#interface NSString (MIMEAdditions)
+ (NSString*)MIMEBoundary;
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict;
#end
#implementation NSString (MIMEAdditions)
//this returns a unique boundary which is used in constructing the multipart MIME body of the POST request
+ (NSString*)MIMEBoundary
{
static NSString* MIMEBoundary = nil;
if(!MIMEBoundary)
MIMEBoundary = [[NSString alloc] initWithFormat:#"----_=_YourAppNameNoSpaces_%#_=_----",[[NSProcessInfo processInfo] globallyUniqueString]];
return MIMEBoundary;
}
//this create a correctly structured multipart MIME body for the POST request from a dictionary
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict
{
NSMutableString* result = [NSMutableString string];
for (NSString* key in dict)
{
[result appendFormat:#"--%#\nContent-Disposition: form-data; name=\"%#\"\n\n%#\n", [NSString MIMEBoundary],key,[dict objectForKey:key]];
}
[result appendFormat:#"\n--%#--\n",[NSString MIMEBoundary]];
return result;
}
#end
/*Connection Delegate Methods*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self.view setUserInteractionEnabled:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
webData = [[NSMutableData alloc] initWithLength:0];
// webData is The NSMutable data
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString* responseString = [[NSString alloc] initWithData: webData
encoding: NSUTF8StringEncoding];
NSLog(#"Response String %#",responseString);
// here i got Authentication failed as Response .....
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
Whenever i run this code getting some Authentication failed error.
I have seen the same issue on various thread. Here is the link I have tried
But unfortunately no luck so far. Please help.
Instead of your own code, you can use ShareKit
It will add full sharing capabilities to your App with just 3 line of code.
ShareKit is an open source framework that can be dropped into any iPhone or iPad app to instantly add full sharing capabilities.
You can use ShareKit to add sharing URLs, images, and text with Tumblr in just a few lines of code.
Sharing Text
+ (SHKItem *)text:(NSString *)text;
NSString *someText = #"This is a blurb of text I highlighted from a document.";
SHKItem *item = [SHKItem text:someText];
You can see more details here

How to integrate Google places Api into our application?

iam developing one application.In that i want to use the google places api.I written the url and established the connection like
NSURL *URL = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=true&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
But in did finish loading delegate method i cant get the data.That code is here.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *parser = [[SBJSON alloc]init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:responseString error:nil];
}
So please tell me where i did the mistake.Why iam not getting the data.
Use ASIHTTPRequest framwork all these problems are automatically handle
all you have to do is just create a url
and parse the response using JSON framework
http://allseeing-i.com/ASIHTTPRequest/
According to my knowledge there are few mistaks.
NSString *responseString = [[NSString alloc]initWithData:responseDataencoding:NSUTF8StringEncoding];
The words responseData encoding are two world. I don't know whether you have pasted like that.
And I hope you have used -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegates to append data to responseData object.
I think you do not need to cast to NSDictionary. You can use following code.
NSString *content = [[NSString alloc] initWithBytes:[responseDate bytes] length:[responseDate length] encoding:NSUTF8StringEncoding];
NSLog(#"Data = %#", content);
NSError *error;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonD = [parser objectWithString:content error:&error];

How to fetch data from webserver using JSON in iphone

i want to fetch data from webserver using JSON and webservice and then parse the JSON Response string.
then i need to insert the data which i have obtained from the webserver into sqlite database.
i have done posting the data to server api database through HTTP post method and this is working properly and my data is getting saved to my server database.And the response that i get is in this format:
{"TokenID":"od28Denamu","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
i need to parse json data and save it in my local sqlite database which consist the same database table as of the server database
this is my code :
//this is used to post the data to web server database through HTTP POST method
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",txtUserName.text,txtPassword.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
//this is my web server api method which consist of 5 parameters Loginkey,Password,DeviceCode,Firmware,IMEI
Loginkey takes Username of user
Password takes password of user
DeviceCode takes device model
Firmware takes device Version
IMEI takes uniqueidentifier of device.
[request setURL:[NSURL URLWithString:#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(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
{
[connection release];
[webData release];
}
//this is used to fetch the data through JSON .
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSString *loginStatus = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
NSArray* latestLoans = [(NSDictionary*)[loginStatus JSONValue] objectForKey:#"Login"];
[loginStatus release];
//get latest loan
NSDictionary* loan = [latestLoans objectAtIndex:0];
//fetch the data
NSString* fundedAmount = [loan objectForKey:#"Loginkey"];
NSString* loanAmount = [loan objectForKey:#"Password"];
NSLog(#"this is foundedamount:%#",fundedAmount);
NSLog(#"this is loanAmount:%#",loanAmount);
//float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];
//NSString* name = [loan objectForKey:#"name"];
//NSString* country = [(NSDictionary*)[loan objectForKey:#"location"] objectForKey:#"country"];
//set the text to the label
//label.text = [NSString stringWithFormat:#"Latest loan: %# from %# needs another $%.2f, please help",
//name,country,outstandingAmount
// ];
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
But the problem when i fetching the data through JSON code is not working,posting to server is working properly.
When i fetch data NSLOG(#"this is foundedamount:null") value is shown .What may be the problem.Please help me in solving this problem.
Thanks
If your problem is to parse a json string, why don't you use a simple json library such as https://github.com/stig/json-framework ?

How to use stringWithContentsOfURL:encoding:error:?

I am trying to use initWithContentsOfURL:encoding:error: like this :
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
I get a empty my_string variable.
I tried the initWithContentsOfURL: method (which is deprecated in iOS 2.0) and I get the content of my page. But I still need to specify a encoding language.
What's wrong ?
Thanks :)
the encoding of your file is probably not UTF8.
If you don't know the encoding of your file, you could try this method:
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
you have to pass a pointer to a NSStringEncoding, like you did with error.:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSStringEncoding encoding;
//NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
// encoding:NSUTF8StringEncoding
// error:&error];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
after this your encoding is present in the encoding variable. If you are not interested in the used encoding, I guess you could pass NULL as pointer as well.
Why not use a request and connection to get the info back in an NSData object? Something like this:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn){
// Data Received
responseData = [[NSMutableData alloc] init];
}
and then in your connection:didRecieveData delegate method, put something like this
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
and then once the connection is finished loading convert the data to a string:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}
Not the most straightforward method, but that should get you your XML string. Also if you need to parse the XML once you get it back, you can directly pass the responseData to an NSXMLParser without any conversion. :)
You can modify your webpage by adding header('Content-Type: text/html; charset=UTF-8'); to the top of the code and saving the document as a UTF-8 formated file. It helped me as I had the same problem.

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:#"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%#&password=%#",#"xxxxxxx",#"xxxxxx"];
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:#"https://secure.school.edu/login/process.do"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"the data %#",string);
}
The whole HTML page is printed twice in the console.So please help me out.Thanks.
You may receive the response data in chunks, which is why NSURLConnection's documentation states:
"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."
Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.
As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(#"data: %#", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}