Implement Timeout in HTTP Post - objective-c

What is the best way to implement a connection timeout (let's say, 20 seconds) within an HTTP post connection?
My current code is as follows:
-(NSData*) postData: (NSString*) strData
{
//postString is the STRING TO BE POSTED
NSString *postString;
//this is the string to send
postString = #"data=";
postString = [postString stringByAppendingString:strData];
NSURL *url = [NSURL URLWithString:#"MYSERVERHERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [postString length]];
//setting prarameters of the POST connection
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request addValue:#"en-US" forHTTPHeaderField:#"Content-Language"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:10.0];
NSLog(#"%#",postString);
NSURLResponse *response;
NSError *error;
NSLog(#"Starting the send!");
//this sends the information away. everybody wave!
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Just finished receiving!");
if (&error) //OR TIMEOUT
{
NSLog(#"ERROR!");
NSString *errorString = [NSString stringWithFormat:#"ERROR"];
urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding];
}
return urlData;
}
Obviously the timeout interval is set to 10.0, but nothing seems to happen when those ten seconds hit.

See:
NSMutableURLRequest timeout interval not taken into consideration for POST requests
Apparently timeouts under 240 seconds are ignored. The highest voted answer in that question links to a solution. However, I would simply recommend using the ASIHTTPRequest library instead.
http://allseeing-i.com/ASIHTTPRequest/

Related

how to consume the json web service in objective c?

i am consuming the json webservice .i am assigning the stringurl to nsurl but the nsurl always assigning the null value. also i didn't get the response. can anyone suggest me what is the mistake i done in the following coding
- (IBAction)addbutton:(id)sender {
NSString *urltest = #"sample url";
NSURL *url = [NSURL URLWithString:urltest];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSString *test= [[greeting objectForKey:#"code"] stringValue];
NSString *test1 = [greeting objectForKey:#"message"];
}
}];}
Your URL string is invalid, note the part:
taxName=ÂU.F¿Kåa¥gh
Those characters are not allowed in URL. Fix your URL to a valid URL (e.g. percent-encode parameter values).
E.g. the above with URL encoding would be:
taxName=%C3%82U.F%C2%BFK%C3%A5a%C2%A5gh
but I am not sure that's correct. The parameter value does not seem to be valid.
Please use this:
NSString *urlString = #"http://localhost:8080/MyWebservice.asmx/GetHelloWorldWithParam";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *myRequestString = #"param="; // Attention HERE!!!!
[myRequestString stringByAppendingString:myParamString];
NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
[request setHTTPBody: requestData];
Thank you

Objective C NSMutableURLRequest GET request returns null JSON

trying get Data from server using #"GET" request,
this following code returns null all time:
is anybody finding an issue with my following code?
or it's can be server side Issue..
?
thank for your help!
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *post = ParamString;
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setURL:[NSURL URLWithString:url]];
NSLog(#"postLength =%#",postLength);
[request setHTTPBody:postData];
[request setHTTPMethod:#"GET"];
[request addValue:ParamString forHTTPHeaderField:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray*jsonReturn = [[NSMutableArray alloc]init];
jsonReturn = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
return jsonReturn;
}
after Editing:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString*StringGETMETHOD = [NSString stringWithFormat:#"%#%#",url,ParamString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:StringGETMETHOD]];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
If you want to use GET for getting response from server just you can try in following method
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
I very much doubt that you should send this parameter as a HEADER field.
I also would think that you should be sending a POST and not a GET.
Setting jsonReturn to [[NSMutableArray alloc] init] is nonsense. Explain to yourself why you are doing it instead of setting jsonReturn to nil
Logging the jsonReturn is nonsense, because all the interesting stuff has disappeared. You should log the response and the data that was returned, at least if jsonReturn = nil.
You seem to be confused between GET and POST. You are doing a GET, but supplying data like a POST (usually does, though it isn't mandated, or precluded to use the body data for a GET).
Generally, you don't want to use body data for a GET, it isn't usual / expected so any number of different issues could be occurring. Either change setHTTPMethod: to #"POST" so you are doing a POST properly, or change the parameters to be part of the request URL.
It really all depends what the server expects (and can handle). This is what you need to know and match against...
Subsequently you have a different issue. The param string you supply has characters in it that need to be encoded (like spaces). Use stringByAddingPercentEscapesUsingEncoding: on the param string before you send it to escape these characters.
It works in a browser because it is adding the escape characters for you (which you should see in the browser address bar after it has loaded the response).
i found my issue:
sending paramString Using "Get" Method, cannot send parameters with space between letters.. example: "tel aviv" should be "tel%20aviv"
by adding the following code line:
**urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];**
fix code:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString* urlParam = [NSString stringWithFormat:#"%#%#",url,ParamString];
urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlParam]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
thank you all !

NSMutableURLRequest returns old values even cachePolicy is NSURLCacheStorageNotAllowed

Im using codes posted here:
connection release method in connectionDidFinishLoading, causes error
now first execute returns didFail log.
second execute; returns old response data.
albeit my (localhost) server is totally offline.
and cachePolicy is NSURLCacheStorageNotAllowed (check the code on the link I posted above)
NSMutableURLRequest *request=
[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f];
the response data seems cached somewhere and still exists.
but if I use NSURLRequestReloadIgnoringLocalAndRemoteCacheData //which is commented as -not implemented-
not returns old cache.
but if so what is the difference between:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData
and
NSURLCacheStorageNotAllowed
what shall I do ?
NSURLCacheStorageNotAllowed refers to NSCachedURLResponse and is an value of enum NSURLCacheStoragePolicy. Since the cache policy of NSMutableURLRequest is also an enum (NSURLRequestCachePolicy) you just pass wrong int to the static method creating NSMutableURLRequest. In this case NSURLCacheStorageNotAllowed is just 2 which equals to NSURLRequestReturnCacheDataElseLoad - and that is why you get old data.
Try This
NSString *Post = [[NSString alloc] initWithFormat:#"Post Parameters"];
NSURL *Url = [NSURL URLWithString:#"Url"];
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];
NSError *error;
NSURLResponse *response;
NSData *Result = [NSURLConnection sendSynchronousRequest:Request returningResponse:&response error:&error];
if (!Result)
{
NSLog(#"Error");
}
else
{
//Parse the result
}

Can't POST a request to service

For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!
It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes
So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.

Put JSON encoded array as NSData from NSURLResponse into NSArray

I'm unable to get this to work:
NSString *post = [NSString stringWithFormat:#"userudid=%#", [udid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
//[udid dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myserver.com/myapp/readtags2.php"]];
[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];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"responseData: %#", content);
is the POST formed correctly? Because i can get it to work from a manual html form posting to the same php file, but i get nothing back when doing it from iOS
You might have an easier time doing HTTP POST's with ASIHTTPRequest.
Form-Posting with ASIHTTPRequest is explained in the section titled "Sending a form POST with ASIFormDataRequest" here: http://allseeing-i.com/ASIHTTPRequest/How-to-use
Otherwise, have a look at the NSURLResponse, check the response code and see if iOS thinks the POST was successful.
Other thing you can use to check is a tool like wireshark to compare the network traffic from your web-based form POST to the traffic from your iOS POST. It looks like you're doing it right, but the best way to be sure is something like wireshark.