iOS Send JSON data in POST request using NSJSONSerialization

淺唱寂寞╮ 提交于 2019-12-04 13:08:29

In your PHP, you're grabbing the $_POST variable, which is for application/x-www-form-urlencoded content type (or other standard HTTP requests). If you're grabbing JSON, though, you should retrieve the raw data:

<?php

    // read the raw post data

    $handle = fopen("php://input", "rb");
    $raw_post_data = '';
    while (!feof($handle)) {
        $raw_post_data .= fread($handle, 8192);
    }
    fclose($handle); 

    echo $raw_post_data;
?>

More likely, though, you want to take that JSON $raw_post_data, decode the JSON into an associative array ($request, in my example below), and then build an associative array $response on the basis of what was in the request, and then encode it as JSON and return it. I'll also set the content-type of the response to make it clear it's a JSON response. As a random example, see:

<?php

    // read the raw post data

    $handle = fopen("php://input", "rb");
    $raw_post_data = '';
    while (!feof($handle)) {
        $raw_post_data .= fread($handle, 8192);
    }
    fclose($handle);

    // decode the JSON into an associative array

    $request = json_decode($raw_post_data, true);

    // you can now access the associative array, $request

    if ($request['firstKey'] == 'firstValue') {
        $response['success'] = true;
    } else {
        $response['success'] = false;
    }

    // I don't know what else you might want to do with `$request`, so I'll just throw
    // the whole request as a value in my response with the key of `request`:

    $response['request'] = $request;

    $raw_response = json_encode($response);

    // specify headers

    header("Content-Type: application/json");
    header("Content-Length: " . strlen($raw_response));

    // output response

    echo $raw_response;
?>

This isn't a terribly useful example (just checking to see if the value associated with firstKey was 'firstValue'), but hopefully it illustrates the idea of how to parse the request and create the response.

A couple of other asides:

  1. You might want to include the checking of the status code of the response (since from NSURLConnection perspective, some random server error, like 404 - page not found) will not be interpreted as an error, so check the response codes.

    You'd obviously probably want to use NSJSONSerialization to parse the response:

    [NSURLConnection sendAsynchronousRequest:postRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            NSLog(@"NSURLConnection sendAsynchronousRequest error = %@", error);
            return;
        }
    
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode != 200) {
                NSLog(@"Warning, status code of response was not 200, it was %d", statusCode);
            }
        }
    
        NSError *parseError;
        NSDictionary *returnDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
        if (returnDictionary) {
            NSLog(@"returnDictionary = %@", returnDictionary);
        } else {
            NSLog(@"error parsing JSON response: %@", parseError);
    
            NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"returnString = %@", returnString);
        }
    }
    
  2. I might suggest that you should use sendAsynchronousRequest, as shown above, rather than synchronous request, because you should never do synchronous requests from the main queue.

  3. My example PHP is doing minimal checking of the Content-type of the request, etc. So you might want to do more robust error handling.

The Advanced Rest Client can be handy to test your web service. So, make sure that web service is acting as desired then map the same parameters in your client app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!