extract data from cocoa http get request - cocoa-touch

I implemented the following code:
NSURL *url = [ NSURL URLWithString:[ NSString stringWithFormat: #"http://www.google.com/search?q=%#", query ] ];
NSURLRequest *request = [ NSURLRequest requestWithURL: url ];
I want to extract the body from what I receive back from the url above. I attempted:
NSData *data = [request HTTPBody];
The data variable doesn't return any data? Am I going about extracting the data out of the request the right way?
Thanks!

If you're just trying to get a web page, you can use this.
NSURL *url = [ NSURL URLWithString: [ NSString stringWithFormat: #"http://www.google.com"] ];
NSString *test = [NSString stringWithContentsOfURL:url];
If you really want to convert the data from NSData you can use this:
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSURLRequest just defines a request — it doesn't do anything by itself. To actually make a request, you need to give the request to an NSURLConnection.
Also, as indicated in the documentation, the HTTPBody is data that's sent with the request, not the response body.

There is an article on www.eigo.co.uk which shows exactly how to do the request and get the response in a string variable but the chunk of code you need is...
NSString * strResult = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
Check out the article here http://www.eigo.co.uk/iPhone-Submitting-HTTP-Requests.aspx

Related

google translate in Objective-C

I have seen some post which uses google translate web page.
NSString* englishString = [englishInputArray objectAtIndex:i];
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|fr",englishString];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:#"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Text: %#",result);
I have two questions:
1)the json return from the web page look like this
[[["Bonjour","Hello","",""]],[["interjection",["bonjour","salut","all\u00f4","tiens"]]],"en",,[["Bonjour",[5],1,0,1000,0,1,0]],[["Hello",4,,,""],["Hello",5,[["Bonjour",1000,1,0]],[[0,5]],"Hello"]],,,[],1]
Other than doing string manipulation is there a way to get the the exact translation string alone ie in tis case "Bonjour" alone.
2: Does anybody know if this is this a free service ? Google apis seems to be a paid service. But if you use web page is that a free service.
No. All API's I've used have always been either JSON or XML. There is no reason to use string manipulation when you can just parse the data into a readable structure
If you are looking to use another service that isn't paid, keep in mind there are normally strict limitations. Try something like: SDL https://www.beglobal.com/developers/api-documentation/
Have you read Google's Translate API Documentation?
https://developers.google.com/translate/
For example performing a GET request like so
GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world
Should return the following response:
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt"
}
]
}
}
With this you can just parse the JSON and display the data

NSData dataWithContentsOfURL erroneous?

Trying to parse simple URL with NSData but fails:
NSURL* url = [[NSURL alloc] initWithString:#"http://192.168.2.105:80"];
NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
Result is
error = Cocoa error 256
What reason?
Check out this:
NSURL* URL=[NSURL URLWithString: #"http://www.google.com"];
NSURLRequest* req=[NSURLRequest requestWithURL: URL];
NSData* data=[NSURLConnection sendSynchronousRequest: req returningResponse: nil error: nil];
That's a short example, I recommend to check out the response and the eventual error.
EDIT
You were right about using dataWithContentOfURL, the code that I posted does the same thing.
But it's the URL to be wrong.You should pass something like http://www.site.org .

Why do I get this error when I try to pass a parameter in NSURL in iOS app?

This is what I have in a public method - (IBAction)methodName
NSString *quoteNumber = [[self textBox] text];
NSURL *url = [[NSURL alloc] initWithString:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quoteNumber];
The error I get is:
Too many arguments to method call, expected 1, have 2
What am I doing wrong?
I think you are thinking of NSString's stringWithFormat::
[NSURL URLWithString:[NSString stringWithFormat:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%#", quoteNumber]]
Also note the change to %# for the format specifier, since it is an instance of NSString (not an int)
You need to format your string. Try this:
NSString *urlString = [NSString stringWithFormat:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%#", quoteNumber];
NSURL *url = [[NSURL alloc] initWithString:urlString];
The initWithString method can only accept a normal NSString, you are passing it a formatted NSString, Take a look at this code:
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quotedNumber]];
That might be a bit confusing, you can break it up as follows:
NSString *urlString = [NSString stringWithFormat:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quotedNumber];
NSURL *url = [[NSURL alloc] initWithString:urlString];
Now your string is properly formated, and the NSURL initWithString method will work!
Also, just so it is clearer for you in the future, you can take advantage of Objective-C's dot notation syntax when you set your quoteNumber string, as follows:
NSString *quoteNumber = self.textBox.text;
Also, you are trying to pass this quoted number into your urlString as a digit (as seen with the %d), remember that quotedNumber is a NSString object, and will crash when you try to pass it to the stringWithFormat method. You must convert the string first to a NSInteger, or NSUInteger.
Please refer to this SO question to how to do that (don't worry it's very easy)!
The problem is
[NSURL initWithString:]
requires ONE parameter of NSString type but you passed TWO parameters .
You need to pass a single NSString parameter . Change your code from
NSURL *url = [[NSURL alloc] initWithString:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quoteNumber];
to
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quoteNumber]];

How to encode sharp sign in NSURL

I have this scenario that I need to send a GET http request to the remote server. I went with NSURLConnection and intercept the request in HTTPScoop.
The url format is something like this:
http://domain.com?key=username##somehash&url=someotherurl.com
I am doing it like this:
NSString *urlString = [[NSString alloc]init];
urlString = #"http://domain.com?key=username##somehash&url=someotherurl.com";
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:encodedString]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
In this case I didn't escape the # sign, and the request I see in httpscoop is:
http://domain.com?key=username223somehash&url=someotherurl.com
If I escape the sharp sign to %23, it gets to something like this in httpscoop:
http://domain.com?key=username22523somehash&url=someotherurl.com
I have tried different combinations but always have issue with the sharp sign. Are there any walk-around for this? Thanks!
replace # with %23 (source).
edit - oops, didn't see the rest of your message. Not sure about NSURL, but I have had difficulty encoding parameters in URLs with NSURL before, too. I ended up using ASIHTTPRequest, which took care of all the encoding issues. I would recommend doing the same.

Creating a POST/GET request using Objective -C [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Tutorials for using HTTP POST and GET on the iPhone in Objective-C
Is there away to create an NSArray with the correct information like id = 1, name = #"John", score = 100 then send it and receive a response from the server?
Maybe display it inside an NSLog();
Can anyone help answer this question by linking me to a good tutorial, I don't want to use ASIHTTPRequest either. I know it would be much simpler but if there is away to do something without using a load of prewritten code id rather learn how to make something using the functionality the the foundation framework offers before going off using someone elses classes.
What you're looking for is NSMutableURLRequest and the addValue:forHTTPHeaderField method.
Create the request with the URL you wish to communicate with. Load the values you wish to transmit into the header or into the HTTPBody, set your HTTPMethod and then use a NSURLConnection method to send and receive the response.
As for an array with the information you could simply enumerate through the array and add the values to the HTTPHeaderFields. It really depends on what the server is setup to receive.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i
Has more information.
NSString *urlString = #"http://yoururl.com";
NSURL *url = [NSUL URLWithString:urlString];
NSMutalbeURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *headerInformation = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"John",#"name",#"100",#"score", nil];
for (NSString *key in [headerInformation allKeys])
{
[request addValue:[dict valueForKey:key] forHTTPHeaderField:key];
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
// this will perform a synchronous GET operation passing the values you specified in the header (typically you want asynchrounous, but for simplicity of answering the question it works)
NSData *responseData = [NSURLConnection sendSynchronousRequest:request reuturningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", responseString);
[responseString release];
It might be easier to just use NSData to send a url request and store the response then to reinvent the wheel. Here is some code similar to something in my production project:
+ (NSData *)getProfiles {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:#"token"];
// Create string of the URL
NSString *serviceURL = [NSString stringWithFormat:#"http://www.myurlhere.com/getProfiles.php?token=%#", token];
NSLog(#"Service URL : %#", serviceURL);
// Create a NSURL out of the string created earlier. Use NSASCIIStringEncoding to make it properly URL encoded (replaces " " with "+", etc)
NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
// Request the url and store the response into NSData
NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
return nil;
}
// Since I know the response will be 100% strings, convert the NSData to NSString
NSString *response = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
// Test response and return a string that an XML Parser can parse
if (![response isEqualToString:#"UNAUTHORIZED"]) {
response = [response stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
data = [response dataUsingEncoding:NSASCIIStringEncoding];
return data;
} else {
return nil;
}
}
NSLog output:
[Line: 476] +[WebSupport getProfiles]: Service URL : http://www.myurlhere.com/getProfiles.php?token=abcdef0123456789abcdef0123456789