我试图将一些POST数据从Objective-c传递到PHP,但PHP文件似乎没有获取数据。将POST数据从Objective-C传递到PHP
下面是我送它:
- (void) sendJSONData:(NSDictionary *)dictData {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:kRootWebService];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
@"IOS TYPE", @"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSLog(@" URL: %@", request);
NSLog(@" Body: %@", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
NSLog(@"%@", httpResponse.allHeaderFields);
if (httpResponse.statusCode == 200) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"This is my print out of data to string\n%@",str);
//deseriealize the return
id JSONObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSDictionary* dictJSON;
NSArray* arrJSON;
NSLog(@"%@", dictJSON);
} else {
NSLog(@"There was an error connecting with the server, the status code returned was %i", (int)httpResponse.statusCode);
}
}];
[postDataTask resume];
}
这里的URL的日志(网址是正确的)和身体:
URL: http://xxxxxxxx.com/xxxxxx.php }
2017-07-30 15:20:10.602 MirrorBox[89680:5646406] Body: {"name":"TEST IOS","typemap":"IOS TYPE"}
这里的请求头的日志
2017-07-30 15:20:10.751 MirrorBox[89680:5646478] {
Age = 0;
Connection = "keep-alive";
"Content-Length" = 34;
"Content-Type" = "text/html";
Date = "Sun, 30 Jul 2017 19:20:10 GMT";
Server = "Apache/2";
"X-Powered-By" = "PHP/5.5.22";
}
这是返回数据的日志,错误信息是我自己的:
This is my print out of data to string
{"key":"could not read POST data"}
这里是PHP文件:
<?php
if (!$_POST['IOS_TYPE']) {
echo json_encode(array("key" => "could not read POST data"));
} else {
echo json_encode(array("key" => "returned string"));
}
?>
我应该提到我有这样的较早,想,也许我是倒着读的钥匙,但我这样做是因为在你的答案我仍然不要击中$ _POST数据 – PruitIgoe
尝试var_dump($ _ POST)并检查真实内容.. – scaisEdge
它是一个空数组 – PruitIgoe