NSURLConnection (Syncronous Request) returns (null) - objective-c

I want to get HTML from website. I wrote below code but this returns (null).
NSString *strURL = #"http://www.googole.com";
- (NSString *)getHtml
{
NSURL *url = [NSURL URLWithString: strURL];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest : req
returningResponse : &response
error : &error];
NSString *strData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return strData;
}

I think you have mistyped the url.
It should be NSString *strURL = #"http://www.google.com";

Related

consuming the string based web service in objective c?

NSString *url = json[0][#"smsapi"];
int ramdomnumber = arc4random_uniform(900000) + 100000;
NSString *msg =#"Your%20Etowns%20verification%20code%20is%20";
NSString *msgstring=[msg stringByAppendingFormat:#"%d ",ramdomnumber];
NSString *outurl = [NSString stringWithFormat:#"%#&mobileNo=%#&msg=%#", url,contactnotextvalue, msgstring];
//calling the web service
NSURLRequest *Request = [NSURLRequest requestWithURL:[NSURL URLWithString:outurl]];
NSURLResponse *resp = nil;
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: Request returningResponse: &resp error: &error];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%# the response......",responseString);
In this above code whenever i will pass the static url i am getting the response but when i add that using stringwithformat i am not getting the response it will pass the null value can anyone suggest me what is mistake i am doing in the above code

How to pass an HTTP as a header in with NSURLSession

I'm trying to submit a GET request from a web service and I want to pass a JSON argument as a parameter in the HTTP header. I have the following code that performs the get request without the JSON argument. How would I add the JSON argument in the HTTP body to pass the JSON parameter?
Heres is my code that works without the JSON argument:
-(void) getReposByDate:(void (^)(NSMutableArray *))handler
{
//Get credentials
NSDictionary *credentials = [KeychainUserPass load:#"APP NAME"];
NSString *userName = [credentials allKeys][0];
NSString *password = credentials[userName];
//Create request
NSString *requestString = #"SOME WEB SERVICE URL";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSData *userPasswordData = [[NSString stringWithFormat:#"%#:%#", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:#"Basic %#", base64EncodedCredential];
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders=#{#"Authorization":authString};
self.session=[NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonObject);
handler([jsonObject valueForKeyPath:#"name"]);
}];
[dataTask resume];
}

Obj-C NSURLConnection not working

So i am trying to send data to a webservice via url with a parameter. the code i have is below but it never hits the server. the request and responses are null. What am i doing wrong?
-(void) postData:(NSString *)data{
NSURLResponse* response;
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:#"http://someaddress.com/api?data=%#", data];
NSURL *lookupURL = [NSURL URLWithString:urlString];
//Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:lookupURL];
NSData *request = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *dataString = [[NSString alloc] initWithData:request encoding:NSUTF8StringEncoding];
NSLog(#"-----------------------------");
NSLog(#"Request: %#", theRequest);
NSLog(#"req response: %#", request);
NSLog(#"response: %#", dataString);}
you want to POST some binary data but you do a GET request and try to put the binary into the url. (without encoding it)
sample post:
NSURL *url = [NSURL URLWithString:#"http://server.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.HTTPBody = postData;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
also, note that the synchronous get is bad as it blocks :) use async networking!

Get data from server using php

NSURL *url = [[NSURL alloc] initWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.php"];
NSData *data = [url resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:data encoding:NSMacOSRomanStringEncoding];
NSLog(#"result FOR ID %#",string);
I am using this code in didenterBackgroundMethod.In that i just want to call lastidretrieve.php which returns a response as a string.I am getting error as "receiver type nsurl for instance message does not declare a method with selector resourceDataUsingCache".i have no idead about this error.
Use this code instead of your code it gives the string output ,then you have to format that string to get disired output.
NSString *post =#"";
NSURL *url=[NSURL URLWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
//NSData *data = [responseData resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
NSLog(#"responseData-%#",string);
}
Output will be like this.
responseData-1995<br />prabu<br />1231231233<br />antab<br />8080808080<br />1360738531881.jpg<br />No
UPDATE
In case you want to add argument in your URL than change post string to this.
NSString *post =[[NSString alloc] initWithFormat:#"yourArg=%#",yourArg];
It would have been sufficient to read the documentation of NSURL. This method is deprecated. You should use [[NSData alloc] initWithContentsOfURL:url] instead.

iphone SDK: How to post data to a url?

This may be a duplicate question but i could not find my answer when searching. So, How do i post data to a url? Heres what i got so far:
NSString *url = #"https://localhost/login.php";
NSURL *urlr = [NSURL URLWithString:url];
NSMutableURLRequest *urlre = [[NSMutableURLRequest alloc] init];
[urlre setURL:[NSURL URLWithString:url]];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSString *user = [defs stringForKey:#"User"];
NSString *pass = [defs stringForKey:#"Pass"];
NSInteger *version = [defs integerForKey:#"Version"];
NSString *bodyData = [[NSString alloc] initWithFormat:#"user=%#&password=%#&version=%d",user,pass,version];
NSData *body = [bodyData dataUsingEncoding:NSASCIIStringEncoding];
NSURLResponse *response = nil;
NSError *error = nil;
[urlre setHTTPMethod:#"POST"];
[urlre setValue:[[NSString alloc] initWithFormat:#"%d",[body length]] forHTTPHeaderField:#"Content-Length"];
[urlre setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlre setHTTPBody:body];
NSData *dataThis = [NSURLConnection sendSynchronousRequest:urlre returningResponse:&response error:&error];
if(dataThis)
{
NSLog(#"Connect Success");
} else {
NSLog(#"%#",[error localizedDescription]);
}
Is the above correct? In my
-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
event, I get nothing. Even in the didFinishLoading it gets nothing with NSLog. Please help.
Have you set a delegate for your request?
Why don't you have a look at using a framework like ASIHTTPRequest, makes things so simple. Check it out http://allseeing-i.com/ASIHTTPRequest/