doumengjing1500 2012-12-14 21:35
浏览 36
已采纳

将JSON从iOS发布到PHP

I've been trying to send JSON data from an iOS app to a mySQL database via a php page. For some reason, my POST data is not available in the php page.

- (IBAction)jsonSet:(id)sender {   
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"firstvalue", @"firstkey", @"secondvalue", @"secondkey", nil];
    NSData *result =[NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSURL *url = [NSURL URLWithString:@"http://shred444.com/testpost.php"];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", jsonRequestData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];

    NSURLResponse *response = nil;
    NSError *error = nil;

    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

I know the php page gets called, and writing to the database is confirmed,

The first couple of lines in my php file grab the POST data

<?php
// Put parameters into local variables
$email = $_POST["firstkey"];
...

but for some reason, $email is also an empty string. I have a feeling the problem is in the iOS code, because I can use APIkitchen.com to test my page and I can confirm it works (only if I exclude the Content-type and Content-Length fields)

  • 写回答

5条回答 默认 最新

  • dpoh61610 2012-12-14 21:40
    关注

    PHP does not decode JSON POST body to $_POST array (so you can't use $email = $_POST["firstkey"];). You need to extract incoming data to array (or object). Lines of code for you PHP-file:

    $jsonString = file_get_contents('php://input');
    $jsonArray = json_decode($json_string, true);
    

    $jsonArray will represent the JSON structure you sent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿