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

7

我目前正在使用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];

500错误通常意味着问题出在服务器上而不是客户端。http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm - Mike D
这里没有太多信息。响应体中有什么? - Jeffery Thomas
@MikeD 在添加 Facebook 安全性之前,它运行得很好,Web 和 Android 版本的应用程序的开发人员都能够与服务器通信。 - Julian Coltea
@JefferyThomas,你能给我响应体的代码片段吗?我会发布我得到的结果。 - Julian Coltea
2个回答

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
你还需要遵循 NSURLConnectionDelagate 协议。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接