From: Alex L. <ale...@gm...> - 2011-05-19 13:53:41
|
Hi, I wrote a very simple Java->iPhone application to open a connection and read the data in the response, but I found I only ever got back 26 bytes of data. Here's the simplest code I could put together which exhibits the problem... private boolean finished = false; @Override public void applicationDidFinishLaunching(UIApplication app) { try { final NSURL url = NSURL.URLWithString("http://www.google.com"); final NSMutableURLRequest req = new NSMutableURLRequest(url); NSURLConnectionDelegate delegate = new NSURLConnectionDelegate() { @Override public void connectionDidFailWithError( NSURLConnection connection, NSError error) { super.connectionDidFailWithError(connection, error); System.out.println("Error [" + error + "]"); } @Override public void connectionDidFinishLoading( NSURLConnection connection) { super.connectionDidFinishLoading(connection); finished = true; System.out.println("Finish loading"); } @Override public void connectionDidReceiveData( NSURLConnection connection, NSData data) { super.connectionDidReceiveData(connection, data); System.out.println("Received data [" + new String(data.getBytes()) + "]"); } }; NSURLConnection.connectionWithRequest(req, delegate); // Wait until all the data has been received or we hit a 20s limit. int i = 0; while (!finished && i < 20) { Thread.sleep(1000); i++; } } catch (Exception e) { System.err.println("Exception doing HTTP" + e); } } I would have expected multiple "Received Data[.......]" messages but I only ever get one of 26 characters. I took a look at the NSData java class, specifically the readData method and I can see why it is failing. The do/while loop in there only continues to read data if its buffer has been filled and assumes that if the read() method returns a read count of less than the buffer size that all the data has been read. Using the code above the response contains an initial 26 bytes and consequently stops as the buffer in NSData has not been completely filled. I wrote an equivalent pure java application and it exhibits the same behaviour using the readData code. Rewriting the readData method so it keeps reading until -1 is returned and buffering the code appropriately retrieves all the data which is approximately 9k bytes. Is this a bug or have I done something wrong? Would the code work properly if the application were running on an iPhone rather than in the Emulator? Thanks, Alex |