No Response from NSURLConnection - ios

I have the following code, which should simply load a URL with post data, and then grab the HTML response from the server:
// Send log in request to server
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#", text_field_menu_username.text, text_field_menu_password.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request;
[request setURL:[NSURL URLWithString:#"http://example.com/test.php"]]; // Example Only
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// Handle response
NSString *response_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data 1: %#", response);
NSLog(#"Data 2: %#", data);
NSLog(#"Data 3: %#", error);
NSLog(#"Data 4: %#", response_string);
}];
Here's the output from each of the NSLog's:
Data 1: (null)
Data 2: (null)
Data 3: (null)
Data 4:
Any idea what I am doing wrong?

You haven't initialized the request object before setting its parameters. It should be:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

Related

Unable to post data to WCF service from iPhone

I am trying to post data to WCF service from iPhone Application but somehow service doesn't seems to be call through the iPhone. I received a Status Code = 999.
NSString *urlString = #"http://192.168.1.192/MSservice/SecureRegistration";
NSURL *URL = [NSURL URLWithString:
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *postData = [bodyData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"Error %#", errorReturned.localizedDescription);
}
else
{
NSLog(#"Data %#", data);
NSString *responseString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response %#", responseString);
}

how to get response on http post method when post html data in ios?

my code here...
not receive all html data....so plz reply me on it:sanandiyavipul#gmail.com
NSString *get_value_key=[NSString stringWithFormat:#"personen=%#&eigenaar=%#&soortwoning=%#&beveiliging=%#&soortdak=%#",[filter_ary4 objectAtIndex:[pickerView4 selectedRowInComponent:0]],[filter_ary7 objectAtIndex:[pickerView7 selectedRowInComponent:0]],[filter_ary8 objectAtIndex:[pickerView8 selectedRowInComponent:0]],[filter_ary9 objectAtIndex:[pickerView9 selectedRowInComponent:0]],[filter_ary10 objectAtIndex:[pickerView10 selectedRowInComponent:0]]];
NSData *postData = [get_value_key dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://media.komparu.com/inboedelverzekering/10045724/5193"]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/html; charset=UTF-8" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody:postData];
// NSError *requestError;
NSURLResponse *urlResponse =nil;
response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[response1 bytes] length:[response1 length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
If you want the response it is in the variable: urlResponse.
If you want the html status code cast the response to NSHTTPURLResponse and access the statusCode property.
Or just create NSHTTPURLResponse instead of NSURLResponse and access directly.
NSError *error;
NSHTTPURLResponse *urlResponse;
response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSInteger statusCode = urlResponse.statusCode;
NSLog(#"statusCode: %i", statusCode);
if (response1) {
// process data
}
else {
// Log the response and error description
NSLog(#"urlResponse: %#", urlResponse);
NSLog(#"error: %#", error);
}

Issue with IOS Http POST

Request data
NSDictionary *tmp = #{#"name":#"Kousik",#"age":#"24",#"location":#"bangalore"};
NSString *postdata = [NSString stringWithFormat:#"request = %#",tmp];
//now postdata is
//request = {
"age" = "24";
"location" = "bangalore";
"name" = "Kousik";
}
but I want this NSDictionary should be inside a string so that in server I can eval it and get the dictionary back.
Here I want something like toString() is java or str() in pyhton.
This is my Http request:-
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *preparedPostData = [postdata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postdata length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:preparedPostData ];
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse response,NSData data,NSError *error){
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if(complect)
complect(result,error);
}
];
Update
My request is going to server properly but The problem is with data structure.
when I am trying to access the data with request key then it is giving error because the value for the request key is not supported in server as this value is having = sign in between. So what I want is that to make the requset data structure properly.want to send the NSDictionary itself as a string.
postdata should be something like this
request = "{
age : 24;
location : bangalore;
name : Kousik;
}"
I dont want to use application/json.
NSString *stringURL = [NSString stringWithFormat:#"name=%#&age=%#&location=%#",#"Kousik",#"24",#"bangalore"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,API_SaveContctListToAddressBook]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[stringURL dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
data = [[NSData alloc] init];
}
NSDictionary *dic =[ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
completionHandler(dic, NO);
}];
Use NSJSONSerialization to convert your dictionary to NSData and then attach it on HTTPBody
NSData *httpBody = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,APIPath]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:httpBody];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//Handling code
}];

xcode using json and POST to validate a username and password

I am new to using POST, and have just written a code that takes a username and password that was entered in and sends it via POST for validation. If it is valid, it will return true, if not it will return false. I think my code works for the most part, but there must be something missing with my return data because it does not output true or false. Here is my code:
- (IBAction)btnLogIn:(id)sender;
{
//getting the username and password and putting it into a string
NSString *post =[[NSString alloc] initWithFormat:#"username= %# &password =%#",[self.lblUserName text],[self.lblPassword text]];
//output the string
NSLog(#"PostData: %#",post);
//setting the URL to post to
NSURL *url=[NSURL URLWithString:#"myurl.php"];
//converts string to data that can be used to post
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//get the length of the string
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
//formatting the URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}
I am not sure what part is missing or wrong. Everything runs fine, just returns blank when I test it out.
this is another method
//Create the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myurl.php"]];
// create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:#"username=%#&password=%#",[self.lblUserName text],[self.lblPassword text],nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}

How to send raw data to API

I have one text field I need to send two data's to API.
NSString *post =[NSString stringWithFormat:#"val1=%#,val2=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"val1"],val2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://api.test.com/send"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"log%#",str);
}
I need to send only raw data to API this is my code.Please check and let me know thanks
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
//error
}
else
{
//no error
}
Try this
Have you tried converting it to NSData and sending that?
Here's the conversion:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
That will give you the data in bytes, then just pass it in with the normal networking function calls.

Resources