1

I am trying to send JSON from my iOS. This is what I have so far:

+ (NSDictionary *)SendJSON:(NSString *)jsonString toAddress:(NSString *)address
{    
    NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:address]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:POSTReply options:kNilOptions error:nil] );
    NSDictionary *jsonresponse = POSTReply ? [NSJSONSerialization JSONObjectWithData:POSTReply options:kNilOptions error:nil] : nil;

    return jsonresponse;
}

It works fine if I send the jsonString like this:

NSString *jsonString = [NSString stringWithFormat:@"username=%@&password=%@", self.txtUsername.text, self.txtPassword.text];

But If I try to send using the JSON format:

@"{ \"username\" : \"%@\", \"password\" : \"%@\" }"

it does not work any ideas why?

PS: This information is being sent to a Rails server.

2
  • The first one isn't a JSON string -- it appears intended to be a URL encoding. The second should produce valid JSON (though it's always hard to tell with the escapes), but of course only if processed through stringWithFormat. The two would not be interchangeable -- they'd have to be transmitted differently.
    – Hot Licks
    Commented Apr 21, 2013 at 20:48
  • Note that you should not send passwords "in the clear", but should use the encrypted password facilities of https or some other protocol.
    – Hot Licks
    Commented Apr 21, 2013 at 20:50

1 Answer 1

3

You probably need to set the Content-Type appropriately since you're sending JSON in the POST body.

This ought to do the trick, replace your x-www-form-urlencoded:

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
1
  • 1
    NO WAY! Thank you, that solved the problem.... I will accept it once I am allowed to.
    – Marcelo
    Commented Apr 21, 2013 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.