【发布时间】:2016-03-02 10:01:26
【问题描述】:
我尝试将NSDictionary 转换为JSON 数据并将其发送到setHTTPBody 在“POST”请求中的PHP.server。
当我从 app 发送时,我从服务器收到了 null,但是当我从 PostMan 发送 JSON 时,我收到了对象。
我哪里错了?
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSString *url = [NSString stringWithFormat:@"http://myAddress/sql_service.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSArray *arrayOfStrings = @[@"alex",@"dima"];
NSDictionary *dict = @{@"request_type" : @"select_with_params",
@"table" : @"user",
@"where" : @"f_name=? OR f_name=?",
@"values" : arrayOfStrings};
NSData* jsonData1 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
[request setHTTPBody:jsonData1];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (data)
{
[receivedData appendData:data];
}
else
{
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error = nil;
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(@"connectionDidFinishLoading");
}
这是我需要发布的 json。
{
request_type: "select_with_params",
table: "user",
where: "f_name=? OR f_name=?",
values: ["dima", "alex"]
}
didReceiveData 中的数据是:
【问题讨论】:
-
您确认
jsonData1不是nil? -
到底出了什么问题?在
NSURLConnectionDelegate的方法中,你收到数据了吗?如果您的回复是顶级的NSArray而不是NSDictionary? -
我编辑问题并添加不为零的图像。
-
我再次编辑问题。
-
connection:connectionDidFinishLoading:被调用了吗?如果是,你能记录下 [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding], or even each time the delegate methodconnection:didReceiveData:` 的值被调用了吗?
标签: objective-c nsjsonserialization nsmutableurlrequest