【问题标题】:Sending HTTP POST JSON parameter to PHP page - iOS将 HTTP POST JSON 参数发送到 PHP 页面 - iOS
【发布时间】:2014-03-27 14:59:00
【问题描述】:

所以我试图通过 POST 将参数发送到 php 服务器,并且该参数值必须是 JSON 值。参数名称必须是“数据”

我的意思是,使用 get 方法类似于 http:url.com/url/something.php?data={"jsonkey1":1,"jsonkey2":[.... 或类似的东西

这是我现在拥有的代码,但我无法让它工作。我不喜欢使用外部库,而是使用本地方法。

// Writing JSON...
NSNumber *imagesCount = [[NSNumber alloc] initWithInt:0];
NSMutableArray *arrayList = [[NSMutableArray alloc] init]; // That's an empty array
//[arrayList addObject:@"image1.png"]; [arrayList addObject:@"image2.png"];
NSDictionary *dictionaryJSON = [NSDictionary dictionaryWithObjectsAndKeys:imagesCount, @"count",arrayList,@"list", nil];

NSString *param = @"data=";
NSMutableData *dataJSON = [[NSMutableData alloc]init];
[dataJSON appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryJSON options:NSJSONWritingPrettyPrinted error:&error];;
[dataJSON appendData:jsonData];

NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@, %@", jsonString, error);

jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// Request to server
NSString *url =[NSString stringWithFormat:@"http://url.com/ios/api/get_images_cache.php?"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%i", [dataJSON length]] forHTTPHeaderField:@"Content-Length"];


NSString* jsonStringdat = [[NSString alloc] initWithBytes:[dataJSON bytes] length:[dataJSON length] encoding:NSUTF8StringEncoding];
jsonStringdat=[jsonStringdat stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStringdat=[jsonStringdat stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSLog(@"Final jsonData as string:\n%@, %@", jsonStringdat, error);
//[request setValue:jsonStringdat forHTTPHeaderField:@"data"];
//[request setValue:jsonData forKey:@"data"];
[request setHTTPBody: [jsonStringdat dataUsingEncoding:NSUTF8StringEncoding]];

感谢您的帮助。

编辑:

我终于做到了,问题出在这两行:

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

我删除了它们,终于让它工作了,谢谢!

【问题讨论】:

    标签: php ios objective-c json


    【解决方案1】:
    NSURLConnection* connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    

    将其添加到最后,然后您需要使您的类符合应用是:

    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
    [request setTimeoutInterval:10];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPBody:postData];
    

    希望对你有帮助!

    编辑: 此外,在发送之前将您拥有的 JSON 转换为字符串。我就是这样做的:

    NSData *dataFromJSON = [NSJSONSerialization dataWithJSONObject:jsonObjects options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:dataFromJSON encoding:NSUTF8StringEncoding];
    

    【讨论】:

    • 我已经建立了连接,但是服务器响应不是我所期望的,我只是没有把它说出来,因为那部分代码运行良好。我还尝试在发送之前将 JSON 转换为 NSSTRING,但没有结果。无论如何感谢您的快速回复!
    • 您是否尝试过向服务器发送虚拟字符串?只是想看看你是否得到回应?
    【解决方案2】:

    您可以在 POST 请求中使用application/x-www-form-urlencoded,您可以在其中发送许多参数(键/值对)。

    请注意,参数键和值必须正确编码。特别是,JSON 通常包含许多不能按原样用作参数值的字符。

    因此,给定一个代表您的 JSON 的对象 jsonRep,它是 NSArrayNSDictionary 对象,您将获得 JSON:

    NSError* error;
    NSData* json = [NSJSONSerialization dataWithJSONObject:jsonRep 
                                                   options:0 
                                                     error:&error];
    

    现在,您需要编码 json。所需的编码算法在这里定义: The application/x-www-form-urlencoded encoding algorithm

    这里是NSDictionary 实现方法dataFormURLEncoded 的类别,它返回一个NSData 对象,表示作为NSDictionary 给出的编码参数(在另一个SO 答案中显示):How to send multiple parameterts to PHP server in HTTP post,例如:

    NSData* paramsData = [@{@"key": @"value"} dataFormURLEncoded];
    

    “参数字典”需要有NSStrings 作为键和值。因此我们需要将 JSON(如 NSData)转换为 NSString(我们知道它的编码是 UTF-8):

    NSString* jsonString = [[NSString alloc] initWithData:json 
                                                 encoding:NSUTF8StringEncoding];
    

    现在我们可以创建“参数字典:”

    NSDictionary* paramsDict = @{@"data": jsonString};
    

    鉴于,链接的 SO 答案中显示了 NSDictionary 类别,我们将参数作为 NSData 对象,正确编码:

    NSData* paramsData = [paramsDict dataFormURLEncoded];
    

    剩下的部分只是创建一个 POST 请求,这是直截了当的:

    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
    [request setURL: url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue: [NSString stringWithFormat:@"%i", [paramsData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: paramsData];
    

    【讨论】:

      【解决方案3】:

      下面的POST和GET代码

          NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://url.com/ios/api/get_images_cache.php?"]];
      
          [request setHTTPMethod:@"POST"];
      
          //Here GIVE YOUR PARAMETERS instead of my PARAMETER
          NSString *userUpdate =[NSString stringWithFormat:@"email_id=%@&pass=%@",txtEmail.text,txtPass.text,nil];
      
          NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
      
          [request setHTTPBody:data1];
      
          NSError *err;
          NSURLResponse *response;
      
          NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
      
          NSString *resultStr=[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
          NSLog(@"resultstr==%@",resultStr);
      
          //You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.    
      
          //After that it depends upon the json format whether it is DICTIONARY or ARRAY 
      
          NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
          NSString *equalilstr=[dict objectForKey:@"message"];
      

      【讨论】:

        【解决方案4】:

        这里是你的预期答案

        第一个编码部分仅用于将数据发布到服务器

        //Here YOUR URL
           NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://url.com/ios/api/get_images_cache.php?"]];
        
        
        //create the Method "GET" or "POST"
           [request setHTTPMethod:@"POST"];
        
        //Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
          NSString *userUpdate =[NSString strin gWithFormat:@"user_email=%@&user_login=%@&user_pass=%@&  last_upd_by=%@&user_registered=%@&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
        
        
        
        //Check The Value what we passed
          NSLog(@"the data Details is =%@", userUpdate);
        
        //Convert the String to Data
          NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
        
        //Apply the data to the body
          [request setHTTPBody:data1];
        
        //Create the response and Error
          NSError *err;
          NSURLResponse *response;
        
          NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
        
          NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
        
        //This is for Response
          NSLog(@"got response==%@", resSrt);
         if(resSrt)
         {
           NSLog(@"got response");
           /* ViewController *view =[[ViewController alloc]initWithNibName:@"ViewController" bundle:NULL];
           [self presentViewController:view animated:YES completion:nil];*/
         }
         else
         {
           NSLog(@"faield to connect");
         }
        

        第二部分是通过 JSON 获得响应

            //just give your URL instead of my URL
        
                NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL  URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
        
               [request setHTTPMethod:@"GET"];
        
               [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
        
                NSError *err;
        
                NSURLResponse *response;
        
                NSData *responseData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&response error:&err];
        
              //Converting data to String for seeing response
                NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
        
              //This is for Response
                NSLog(@"got response==%@", resSrt);
        
              //You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.    
        
              //After that it depends upon the json format whether it is DICTIONARY or ARRAY 
        
                NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
        
                NSArray *array=[[jsonArray objectForKey:@"search_api"]objectForKey:@"result"];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多