fail to get http web server response

Hi all,

I create a java web http server , and ios client send HTTP GET request to the web http server using NSURLConnection, then the server send back 200 OK response to the ios client. When I run my app on the iPhone simulator, everything is OK , my app can receive the response from the web http server for such progress:

1. My app call this callback function: -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

In this callback function, the "data" contains exactly the body of the 200 OK response packet.

2. My app then call this callback function: -(void)connectionDidFinishLoading:(NSURLConnection *)connection;

In this callback function, I think I have received all the data of response packet and do my job next...


But when I run my app on REAL Device(such as iPhone4s, iPad air, iPhone6), my app just call step 1 callback function: -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data, and not to call step 2, so I cannot do my job next.


There should be something wrong with my java web http server, but I do not know what is wrong. I have send the valid HTTP 200 OK packet:

Date now = new Date();

int len = 294;

String lenHeader = "Content-Length: " + len + "\r\n";

String dateHeader = "Date: " + now.toString() + "\r\n";

String message = "HTTP/1.1 200 OK\r\n"

+ "Content-Type: application/json\r\n"

+ "Server: Jerry Web Server\r\n"

+ "Connection: keep-alive\r\n"

+ lenHeader

+ dateHeader

+ "\r\n"

+ content; /*content is the body of the 200 OK packet*/

System.out.println("the message is \r\n " + message);

try {

output.write(message.getBytes());

output.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Do you get an error back from NSURLConnection? That would be surfaced via the

-connection:didFailWithError:
delegate callback.

btw Why are you using NSURLConnection? It’s recently been deprecated in favour of NSURLSession, so if you’re writing new code you should just use that. And NSURLSession makes it really easy to issue simple HTTP requests. Here’s a minimal example:

[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com"] completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
    if (error != nil) {
        NSLog(@"transport error %@", error);
    } else {
        NSHTTPURLResponse * responseHTTP;

        responseHTTP = (NSHTTPURLResponse *) response;
        if (responseHTTP.statusCode != 200) {
            NSLog(@"server error %d", (int) responseHTTP.statusCode);
        } else {
            NSLog(@"data %@", data);
        }
    }
}] resume];

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
fail to get http web server response
 
 
Q