Sending HTTP POST request in iOS with JSON

So I'm currently using Facebook to login to my iOS app, and the server administrator recently added security authentication by requiring a Facebook access token along with making all connections go via https. Here's the code I've tried running, but I've been getting a server response error of 500 (internal server error) no matter what I do. Any ideas?

NSMutableURLRequest *request = [NSMutableURLRequest
                                requestWithURL:[NSURL URLWithString:@"https://XXXXXXXXXXXXXXXX/users.json"]];

NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:
                     userID, @"facebook_id",
                     FBAccessToken, @"fb_token",
                     userName, @"name",
                     nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

以下是您如何记录响应主体。

@property (strong, nonatomic) NSMutableData *responseData;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.responseData = [NSMutableData data];
    …
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
    …
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"response data - %@", [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]);
    …
}

您还需要符合NSURLConnectionDelagate协议。

链接地址: http://www.djcxy.com/p/70098.html

上一篇: for循环和for之间的区别

下一篇: 使用JSON在iOS中发送HTTP POST请求