Timeout doesn't work properly in the NSMutableURLRequest. But, why? - iphone

NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:#"application/x-www-form-urlencoded;charset=utf-8" forKey:#"Content-Type"];
[headers setValue:#"text/html" forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT_REQUEST];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
[self createConnectionWithRequest:request delegate:delegate];
My TIMEOUT_REQUEST=30 seconds , but sometimes i'm waiting for 80 seconds before I'll get didFailWithError. But, why?

Related

Login credential issue using NSURL Methods

I have an webservices url which appends with password. When I run the application by giving correct password, the application is running and at the same time when I run the app with wrong credentials. the app is running, I didn't have an idea to get rid out of the issue. My code is here:
NSString *post =[[NSString alloc] initWithFormat:#"password=%#",[password text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/Accountservice/Secure/ValidateAccess?password=abcd&type=1"]];
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 setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:post] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self startImmediately:YES];
if(!connection){
NSLog(#"connection failed");
}
else{
NSLog(#"connection succeeded");
}
If I gave 'abcd' as password connection is successfully is displaying. If I gave wrong password connection successfully is displaying. How can I solve the issue? If I gave wrong password need to display an alert.
This control structure here is the problem:
if(!connection){
NSLog(#"connection failed");
}
else {
NSLog(#"connection succeeded");
}
This doesn't check for a bad connection, this checks whether or not the connection object is equal to 0 (nil). Obviously, having initialized it on the line above, the else statement will always log, giving you the false impression that your connection had succeeded. You should become the connection's delegate, and respond to the appropriate delegate methods instead.
The issue may be with the url you are using
Fire the url in the browser and see what it returnes
try add the url params with single quotes accesscode='abcd'
It is not a good practice to pass the credentials via this way.
You could use POST method with some valid encryption to prevent the security issues that can occur
SOLUTION
Try this
NSString *urlString=#"http://myexample.com/Accountservice/Secure/ValidateAccess?";
self.responseData = [NSMutableData data];
NSString *post =[NSString stringWithFormat:#"username=%#&password=%#",userNameTextField.text,passwordTextField.text];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection0= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection0 start];

I am sending dictionary in json and its have two array and multiple value but i am getting response access denied

I am sending two array and multiple value throw json but when i send this i am getting success code 200 and its response showing access denied pls any one give me right way to solve it **
-(void)SaveColumnConnection
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURLURLWithString:#"http://xxxyyyzzzz.php"]];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:oneRowColumn,#"oneRowCols",memberTid,#"table_title_id",totalRowStr,#"totRow",rowandColumn,#"tempColName",tableOptIdArray ,#"tempOptid",companyId,#"companyid",#"savecolumniphone",#"tag",nil];
NSLog(#"dict %#",dict);
SBJSON *parser =[[SBJSON alloc] init];
NSString *jsonString = [parser stringWithObject:dict];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [HTTPResponse statusCode];
if (statusCode==200) {
//Request goes in success
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json for post array ----------%#",str);
}
else{
///request is get failed
NSLog(#"Error Description %#",[error localizedDescription]);
}
}];
[request release];
}
Wanted to see your php code as well..Anyways please check whether the following example helps you out... Here I am not sending any dictionary values, adjust the code to your requirement :)
NSString *jsonRequest = #"{\"username\":\"user\",\"password\":\"pwd\"}";
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://xxxyyyzzzz.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
try this code
NSDictionary *dict = [NSDictionary
dictionaryWithObjectsAndKeys:oneRowColumn,#"oneRowCols",memberTid,#"table_title_id",totalRowStr,#"totRow",rowandColumn,#"tempColName",tableOptIdArray ,#"tempOptid",companyId,#"companyid",#"savecolumniphone",#"tag",nil];
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:#"http://xxxyyyzzzz.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

How to show UIProgressView with ASIFormDataRequest

I want to show uiprogress bar with ASIFormDataRequest. I googled it but i can't find regarding uiprogressView with ASIFormDataRequest, I just find uiprogressView with NSURLConnection. just let me know if it is possible.
// So this my method where i upload the data.
-(NSMutableArray*)getUploadVideo:(NSString*)titleName userID:(NSString*)userId token:(NSString*)tokenID description:(NSString*)desc videoID:(NSString*)video_id privateOrPublic:(NSString*)privacyID pathOfVideoFile:(NSString*)path mode:(NSString*)potLand;
{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://%#/aircastdev/RestServices/fileUpload"],kId];
[request setDelegate:self];
[request setDidFailSelector:#selector(uploadFailed:)];
[request setDidFinishSelector:#selector(uploadFinished:)];
[request setDidFinishSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setPostValue:titleName forKey:#"title"];
[request setPostValue:userId forKey:#"user_id"];
[request setPostValue:tokenID forKey:#"token"];
[request setPostValue:desc forKey:#"desc"];
[request setPostValue:video_id forKey:#"video_id"];
[request setPostValue:privacyID forKey:#"is_private"];
[request setPostValue:potLand forKey:#"mode"];
NSString *url = [[NSURL fileURLWithPath:path] path];
[request setFile:url withFileName:[NSString stringWithFormat:#"%#.mov",titleName] andContentType:#"video/MOV" forKey:#"file"];
[request setTimeOutSeconds:50000];
[request setRequestMethod:#"POST"];
// EDITED LINE
[request setUploadProgressDelegate:myProgressView];
[request startSynchronous];
SBJSON *sbJason = [[SBJSON alloc] init];
getUploadArray = [sbJason objectWithString:self.response];
return getUploadArray;
}
// when upload is done this method call.
- (void)requestFinished:(ASIHTTPRequest *)request
{
// alert: request is successfully sent
self.response = [request responseString]; //stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
use this:
[request setDownloadProgressDelegate:progressView];
or
[request setUploadProgressDelegate:myProgressIndicator];
Where progressView is a UIProgressView
also have a look here

i want to send request by POST on iPhone,but the body can't be received by server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iPhone SDK Xcode 4.2 iOS 5- How do i send a json to url ? (POST not GET) [Resolved]
NSDictionary *requestDic=[NSDictionary dictionaryWithObjects:values forKeys:keys];
NSString *jsonreq=[requestDic JSONRepresentation];
NSURL *requrl=[NSURL URLWithString:[NSString stringWithFormat:#"%#index.php?r=%#&te=%#&noCheck=1&checkInstall=start",[Info serverUrl],[dictParameters objectForKey:#"r"],[dictParameters objectForKey:#"te"]]];
requrl = [NSURL URLWithString:[[requrl absoluteString] stringByAppendingString:subUrl]];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:requrl];
[req setHTTPMethod:#"POST"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json-x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *requestData=[NSData dataWithBytes:[jsonreq UTF8String] length:[jsonreq length]];
[req setHTTPBody:requestData];
[browser loadRequest:req]
Dilshand's answer is ok , but you can use ASIFormDataRequest for ease. like follow
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:mobileApplicationId forKey:#"mobileApplicationId"];
[request setPostValue:mobileApplicationVersion forKey:#"mobileApplicationVersion"];
[request setPostValue:userID forKey:#"userId"];
[request setPostValue:pass forKey:#"password"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
What you want to post server give complete detail and what error you are getting
try following i have done using this to send data to server and it works fine for me hope this helps
NSString *post =[[NSString alloc] initWithFormat:#"ProviderNPI=%#&PatientID=%#&FileURL=%#&FileTYPE=%#&DataSynID=%#& AppointmentListingsID=%#",providerNPI,patientID,FILEURL,FILETYPE,dataSynID,appointmentListingID];
NSURL *url=[NSURL URLWithString:#"http://myserver.com/Sync.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 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 *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
NSURL *url = [NSURL URLWithString:#"http://www.invoicera.com/app/api/check_json_api.php?token=7B92C122473A3D6F54E60D20AC5526D0"];
NSString *jsonRequest = [NSString stringWithFormat:#"&json_data=%#",[[NSString stringWithFormat:#"{\"listInvoice\":{\"client_id\":\"\",\"date_from\":\"\",\"date_to\":\"\",\"invoice_number\":\"\",\"invoice_record_status\":\"\",\"invoice_status\":\"\",\"page\":\"1\",\"per_page_record\":\"20\"}}"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",jsonRequest);
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSLog(#"%#",json_data);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: json_data];
NSLog(#"%#",json_data);
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [json_data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
// [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
// Successful connection.
if (nsUrlConnection) {
// [self initSpinner];
// [self spinBegin];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData=data;
[data release];
}
// Unsuccessful connection.
else {
}
// Clean up
[url release];
[request release];
// Close keypad.

how to write data on server?

i am making a registration page were user can register?
this is my code..............
-(IBAction)btn_log:(id)sender
{
//NSString* username = nameInput.text;
//NSString* pass = passInput.text;
NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;
NSString *post =
[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#",firstname,lastname,bname];
//NSString *post = [[NSString alloc]initWithFormat:#"fname=firstname&lname=lastname&email=bname];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
}
But it's not working so please can anyone suggest me where i am making mistake.
try in this way may be it will help you
Nsurl *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
nsstring *body = [nsstring stringwithformat:#"%#,%#",nameinput,paasinput];
nsmutableurlrequest *request = [nsmutablerequest alloc]initwithurl:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request sethttpbody:[body dataysubgebcidubg:asciiiencoding allowlossyconversion : true]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Replace above line of your code with following line. Probably it will work.
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];