【发布时间】:2016-12-30 20:37:28
【问题描述】:
当软件通过构造函数初始化并在软件控制台内显示结果时,我有一些软件通过 Objective-C 向我发送 JSON 数据:
- (id)initWithAPIManager:(id)apiManager
{
_apiManager = apiManager;
NSString *strURL = @"http://mysite/DBTest.php";
NSLog(@"URL:\t%@", strURL );
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
NSString *jsonData = [NSString stringWithFormat:@"{\"IP\":\"%@\",\"Date\":\"%@\"}",
[self GetIP],
[self GetDate]];
NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
length:[jsonData lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:requestData];
NSLog(@"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
//- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))
//[NSURLConnection dataTaskWithRequest:]
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];
if ( responseData != nil ) {
NSLog(@"responseData is valid.");
NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"myString:\t%@", myString);
} else {
NSLog(@"responseData is nil!");
}
} else { // uh oh
NSLog( @"Error creating the URL request!" );
}
//NSLog(@"IP address:\t%@", [self getIP] );
OldIPGettingThingy();
return self;
}
当我使用本地 JSON 文件时,我的 PHP 脚本可以正常工作,但是当我切换到使用 php://input 时,我的 var_dump 显示为 NULL,并且我没有任何内容插入到我的数据库中。提前致谢。
<?php
$con = new PDO('mysql:host=localhost;dbname=pirates','root','password');
//$raw_data = file_get_contents('php://input');
$raw_data = file_get_contents('tes.json');
$data = json_decode($raw_data, true);
var_dump($data);
$stmt = $con->prepare("INSERT INTO Tracking values(?,?,?)");
foreach ($data as $row){
$stmt->bindParam(1, $row['id']);
$stmt->bindParam(2, $row['IP Address']);
$stmt->bindParam(3, $row['timestamp']);
$stmt->execute();
}
echo "got here";
?>
【问题讨论】:
-
从不自己构建 JSON。使用 JSON 序列化器,并为其提供字典或其他复杂对象。这将为您将来省去很多麻烦。
标签: php mysql objective-c json