使用JSON在iOS中发送HTTP POST请求

时间:2013-03-12 02:33:00

标签: ios json facebook http post

所以我目前正在使用Facebook登录我的iOS应用程序,服务器管理员最近通过要求Facebook访问令牌以及通过https进行所有连接来添加安全身份验证。这是我尝试过运行的代码,但无论我做什么,我的服务器响应错误都是500(内部服务器错误)。有什么想法吗?

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];

2 个答案:

答案 0 :(得分:3)

以下是您记录响应正文的方式。

@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]);
    …
}

答案 1 :(得分:1)

您还需要符合NSURLConnectionDelagate协议。