0

when i want to post json to the web server, it will crash and show:

Warning, status code of response was not 200, it was 400
2014-03-20 01:15:54.407 iBeacons[6669:60b] error parsing JSON response: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x156b6440 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

2014-03-20 01:15:54.408 iBeacons[6669:60b] returnString:

400 Required String parameter 'beaconsMapping' is not present Required String parameter 'beaconsMapping' is not present

    if ([NSJSONSerialization isValidJSONObject:sendData]) 
    {
    NSError *error;
    NSLog(@"1");
    NSData *jsonData=[NSJSONSerialization 
    dataWithJSONObject:sendData options:
    NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];
    NSLog(@"2");
    NSString *json=[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",json);
    NSString *reqData=[@"beaconsMapping=" stringByAppendingString:json];
    NSLog(@"%@",reqData);
    NSData *postDatas=[NSData dataWithBytes:[reqData UTF8String] length:[reqData length]];
    NSString *postLength=[NSString stringWithFormat:@"%d",[postDatas length]];
    NSMutableURLRequest *requestPost=[NSMutableURLRequest requestWithURL:dataUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    NSLog(@"%@",dataUrl);
    [requestPost setHTTPMethod:@"POST"];
    [requestPost setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [requestPost setValue:@"application/json"forHTTPHeaderField:@"Accept"];
    [requestPost setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    [requestPost setHTTPBody:postDatas];

    NSError *requestError=nil;
    NSURLResponse *response = nil;
    NSData *data=[NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&requestError];
    if (requestError == nil) {
        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 *error;
        NSDictionary *returnDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (returnDictionary) {
            NSLog(@"returnDictionary=%@", returnDictionary);
        } else {
            NSLog(@"error parsing JSON response: %@", error);

            NSString *returnString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
            NSLog(@"returnString: %@", returnString);
        }
    } else {
        NSLog(@"NSURLConnection sendSynchronousRequest error: %@", requestError);
    }


}

//my json output:

beaconMapping=[
    {
        "floorplanId": "mcc",
        "id": "mcc.b",
        "beaconIds": [
            {
                "distance": "3.873",
                "beaconId": "identityId:Major: 44643, Minor: 29271 x:23.6 y:-21.3 z:-50.2"
            }
        ],
        "locationId": "b"
    }
]//thewebserverrequirestheformatlikethat
 [
    {
        "floorplanId": "mcc",
        "locationId": "c",
        "id": "mcc.c",
        "beaconIds": [

        ]
    },
    {
        "floorplanId": "mcc",
        "locationId": "b",
        "id": "mcc.b",
        "beaconIds": [
            {
                "beaconId": "identityId:Major: 44643, Minor: 29271 x:58.0 y:124.6 z:-360.3",
                "distance": "3.202"
            }
        ]
    },
    {
        "floorplanId": "mcc",
        "locationId": "a",
        "id": "mcc.a",
        "beaconIds": [

        ]
    }
]

// my websever post code :

    @RequestMapping(value = "/beacons/{floorplanId}", method = RequestMethod.POST)
public @ResponseBody
Set<BeaconsAtFloorplanLocation> setBeacons(
        @PathVariable("floorplanId") String floorplanId,
        @RequestParam("beaconsMapping") String beaconMappingJson)
        throws Exception {

    Set<BeaconsAtFloorplanLocation> beacons = (new MCCObjectMapper())
            .readValue(beaconMappingJson,
                    new TypeReference<Set<BeaconsAtFloorplanLocation>>() {
                    });

    beaconsLoader_.setBeaconMapping(floorplanId, beacons);

    return beacons;
}
user2765393
  • 9
  • 1
  • 6

4 Answers4

1

Try removing

Content-Length

Accept

and

Content-Type

from your code. It may help you. I had the same issue with json WCF, though my json object was valid json. I removed all those 3 from code and it worked. The server was not accepting those. I dont know why..

Cheers

Sabby
  • 2,586
  • 2
  • 27
  • 41
0

You're not offering the right format data when encoding your json probably.

Are you using json serialization?

Try to use NSLog to see if your data is correct before doing it, you create a NSError *error and put it in your json encode to check what is going on before you post it for your webserver.

Kio Coan
  • 561
  • 2
  • 7
  • 24
  • yes, when output data seems right and i post my code and json format, and could u help me check it again? thanks! – user2765393 Mar 20 '14 at 15:50
0

I have solved this problem, delete

[requestPost setValue:@"application/json"forHTTPHeaderField:@"Accept"];
[requestPost setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];

it will work.

codercat
  • 22,873
  • 9
  • 61
  • 85
user2765393
  • 9
  • 1
  • 6
0

You can get this issue if you're connected to VPN on your device.

codeburn
  • 1,994
  • 17
  • 20