I have the following code:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://some-example-domain.com/api"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
[NSURLConnection sendAsynchronousRequest:theRequest
queue: [NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error && data) {
// success!! - no errors and data returned
NSLog(#"success");
} else {
// error!! - something whent wrong
NSLog(#"failure: %#", [error localizedDescription]);
}
}
];
which works well - except for odd occasions when the server only sends part of the desired response (eg. half of a JSON response from an API) (it still is 'successful' according to my 'if' statement)
Is there some way using this block based method that I can check to see that the data received is complete??
I have tried looking into the NSURLResponse *response - but can't quite figure out how to use it (or, if it is indeed useful in this scenario). Any ideas on how to test for 'partially received' data returned by the block?
There are potentially two different failure modes for this query that aren't handled, and you'll need to check for them separately:
"successful" HTTP connection, but an malformed response
"successful" HTTP connection, but status code indicates a problem on the server
In the case of NSURLConnection, the error is only set when the connection fails, not when a problem is reported from the server (for example: a 404 error or a 330 response).
Generally, when you are talking to an HTTP or HTTPS service, you'll need to check the -statusCode in the NSURLResponse, which in the case of these services will actually be an NSHTTPURLResponse. If there's an error on the server, such as 408 for request timed out on the server, you need to handle that separately from a connection failure (which will cause the error to be set).
Even if you get back a nice [response statusCode] == 200, you will likely still want to check for malformed responses, which you'll need to do when you parse the data that comes back. This is a less likely scenario, but if the server is flakey, you may get a partial response or an encoding failure.
Related
I am experiencing an issue on iOS 4.3+ with ASIHTTPRequest where a request is fired but no data (Request methed, url, headers, etc) reaches the server. The connection times out because it never hears back.
The server hears the empty request (after some delay), then hears a valid request which is of course never reported to higher level code because the connection has timed out. This is all kind of strange because the request was not configured to resend data.
Often this happens after the app has been pushed to the background for some time (15 min or more) and the phone has been allowed to sleep.
My configuration of the request is as follows:
NSMutableData *postData = nil;
NSString *urlString = [NSString stringWithFormat:#"%#%#",[self baseURL],requestPath];
OTSHTTPRequest *request = [OTSHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setTimeOutSeconds:45];
//Set up body
NSString *queryString = [self _RPcreateQueryString:query];
if ([queryString length]>0) {
if(method == RPAsyncServerMethodPost || method == RPAsyncServerMethodPut){
postData = [[[queryString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] mutableCopy] autorelease];
}else{
NSURL *url = [NSURL URLWithString:[urlString stringByAppendingFormat:#"?%#",queryString]];
[request setURL:url];
if (!url) return nil; //url String malformed.
}
}
// ... ///
// method setting stripped for brevity
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
if(headers){
for (NSString* head in headers) {
if ([[headers valueForKey:head] isKindOfClass:[NSString class]])
[request addRequestHeader:head value:[headers valueForKey:head]];
}
}
[request addRequestHeader:#"Content-Length" value:postLength];
[request setPostBody:postData];
OTSHTTPRequest is simply a subclass of ASIHTTPRequest that contains properties for a string tag, a pretty description, and other bling for use by consuming objects and does not override any ASI stuff.
Can anyone shed a light on why/how ASI could open a connection and then send absolutely nothing for minutes at a time?
Edit: Just to clarify. The connections DO make contact with the server, it just never sends any data through the connection from what my server logs can tell. This seems to always happen on app wake and effects all connections including NSURLConnections spawned by MapKit. the whole app just seems to loose its marbles.
I also see a bunch of background tasks ending badly right before this, but i can never catch them while in the debugger.
It doesn't look like you are starting your request based on the code that you have provided. Try call the -[startSynchronous] or -[startAsynchronous] methods of your OTSHTTPRequest object after you are done setting its various properties.
Are you setting the delegate, either I overlooked it or you stripped it out.
I didnt want to say anything till a few days passed with out the issue. The solution in this case was very obscure.
It appears the version of TestFlight i was using has a bug in it that may have contributed to this issue. Since its removal i have not experienced the issue.
in ASIHTTPRequest class
I debug - (void)main method of the NSOperation with wireshark . I want to find which method send data.
But i debug to the end of startRequest in main method of NSOperation. I can't grab any data.
Because the read stream opens a socket connection with the server specified by the myUrl parameter when the CFHTTP request was created, some amount of time must be allowed to pass before the stream is considered to be open. Opening the read stream also causes the request to be serialized and sent.
base the above document of apple about "Communicating with HTTP Servers"
the most chance to send data is the below code .But it don't. I can't find something in wireShark.
CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
if (CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt)) {
if (CFReadStreamOpen((CFReadStreamRef)[self readStream])) {
streamSuccessfullyOpened = YES;
}
}
where send data ???? like socket send or sendto function.
[request startAsynchronous];
and
[request startSynchronous];
If your program is for command line, just use [request startSynchronous] in main, because if you use asynchronous request, the main thread continue, when main thread terminate, maybe asynchronous request do nothing.
Before I dive into ASIHttpRequest's source code:
From the documentation (http://allseeing-i.com/ASIHTTPRequest/How-to-use) of ASIHttpRequest it is not completely clear to me when an ASIHttpRequest will call requestDidFinishSelector or requestDidFailSelector.
When does a request fail?
Is it correct to assume that whenever the server responds (with a corresponding HTTP status code, be it a 1xx, 2xx, 3xx, 4xx or 5xx, the request is considered successful, and therefore requestDidFinishSelector will apply?
Is 'failure' the fact that the server could not be reached?
As I type this, this seems to be the most logical answer... anyway.
Yes, ASIHTTPRequest doesn't use HTTP status codes (except for redirection), so it's up to you to look out for problems (ex: 404) in your requestDidFinishSelector selector.
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
requestDidFailSelector will be called only if there is the server can not be reached (time out, no connection, connection interrupted, ...)
You're right — a request succeeds if the server responds with a HTTP status code. You can ask for this status code by using ASIHTTPRequest's responseStatusCode.
If the request URL is invalid or your app has no access to the Internet, then your request fails. So you should implement requestDidFailSelector (or specify your own error handling method) and handle errors in there in any case.
I am currently doing many server side computations that take a while to process.
In the mean time I redirect the user to the same page until it has a response.
This is resulting in a "too many HTTP redirects" error. Is there a way to disable this, or increase its threshold?
This happens on the simulator and on the phone.
here is the relevant code:
//Define request
NSURLRequest *request = [requestGenerator theRequest];
// Execute URL and read response
NSError *error = nil;
NSHTTPURLResponse *httpResponse;
NSData *resp = [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:&error];
//If we get a good response
if(resp != nil && httpResponse != NULL && [httpResponse statusCode] >= 200 && [httpResponse statusCode] < 300)
{
...
}
if (error) {
[self showErrorMessage:error];
}
Redirecting to the same URL is extremely wasteful. At the very least, assign the "job" an ID and return that to the calling app. It can then poll the server, passing up the ID, to see when the job completes. You should not poll too frequently, perhaps once every few seconds.
You can also just use a single request-response. Your server will simply not respond until it has the data. On the iPhone the default time-out is set to 60 seconds. Your server may be able to start a response (write out a little data) so the connection is established; but do not complete & close the connection until processing completes.
Finally, if you do a simply request ... long delay ... response; and expect it will take > 60 seconds - consider extending the timeout of the request via NSMutableURLRequest's setTimeoutInterval.
Note: in your example you are using a synchronous request. If you do that outside of a thread, your app can block. If it blocks for > 20 seconds, it will be killed by the watchdog service. It's very easy to use the asynch methods with delegates to catch the responses, so give them a whirl.
Finally, if you use the asynch methods; you can catch the 3xx redirect and handle it yourself; but you know, your redirect technique seems evil so don't do it.
I am downloading images using the NSURLConnection sendSynchronousRequest method and that works fine. However, occasionally I run into an issue where the image URL points to something other than an image file. For example, I found this non-image URL was causing issues: http://www.100plusposters.com/images/ExoticFlowers.jpg The URL returns a Web page, which I assume occurs because the image is missing from the site.
One nice thing about Objective-C is that the invalid image doesn't cause a crash. It simply and quietly continues along and just doesn't display any image, but that is still a problem.
How can I validate the data returned to ensure it is a valid image file before displaying it?
Thanks!
My relevant code, in case that helps...
NSError *error = nil;
NSURLResponse *response;
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(data != nil && [error localizedDescription] == nil)
{
//Create UIImage object using initWithData method
//Display UIImage
}
Looks like NSURLResponse object contains a MIMEType property. That should give you a pretty good idea what the type of the returned data is.
Could we take this question one step further? What if the image data is incomplete or corrupt from the server? The complete transport works, the MIME type is image/jpeg, the UIImage is constructed and non-nil but the renderer discovers inconsistencies in the data and the log may show "Bad Huffman code" or "premature end of data segment"
How would I capture this error before tossing the UIImage into the view context and thereby getting a not-pretty image on the screen?
I think by crosschecking the content length obtained from the header of the Http Request and finally recieved data would give you, whether the data downloaded was complete or not.
About the corrupt i dont have much info.