I have some software that is sending me JSON data via objective-C when the software initializes through a constructor and it is displaying the results inside the console of the software:
- (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;
}
I have a PHP script that is working correctly when I use a local JSON file but when i switch to using php://input my var_dump says NULL and I have nothing inserting into my database. Thanks in advance.
<?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";
?>
I figured out the issue was with the objective-c code and I needed to use a dictionary instead of a string format:
- (id)initWithAPIManager:(id)apiManager
{
_apiManager = apiManager;
NSString *strURL = @"http://myip/DBTest.php";
NSLog(@"URL:\t%@", strURL );
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
NSDictionary *dict = @{ @"IP" : [self GetIP],
@"Date" : [self GetDate]};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
length:[jsonData lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPMethod:@"POST"];
//[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestData];
NSLog(@"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];
if ( responseData != nil ) {
NSLog(@"responseData is valid.");
NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"myString:\t%@", myString);
} else {
NSLog(@"responseData is nil!");
}
} else { // uh oh
NSLog( @"Error creating the URL request!" );
}
return self;
}
And my PHP:
<?php
$host = "localhost";
$userid = "root";
$password ="password";
$database = "database";
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$request_data = json_decode($raw_post_data, true);
header("Content-Type: application/json");
$mysqli = new mysqli($host, $userid, $password, $database);
if ($mysqli->connect_errno) {
echo json_encode(array("success" => false, "message" => $mysqli- >connect_error, "sqlerrno" => $mysqli->connect_$
exit();
}
$sql = "INSERT INTO table (IP,Date) VALUES (?,?);";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $request_data["IP"], $request_data["Date"]);
if (!$stmt->execute())
$response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate"$
else
$response = array("success" => true);
$stmt->close();
} else {
$response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $
}
$mysqli->close();
echo json_encode($response);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.