【问题标题】:JSON POST is not working in iOsJSON POST 在 iO 中不起作用
【发布时间】:2012-11-01 19:08:29
【问题描述】:

我正在尝试使用 JSON POST 方法将一些数据发布到 Web 服务,我已经尝试了很多方法来做到这一点,但没有一个有效。这是我的代码,请检查:

    NSArray *objects=[NSArray arrayWithObjects:@"value1", @"value2",@"value3", @"value4",@"value5", @"value6",@"value7", @"value8",@"value9", nil] ;
    NSArray *keys=[NSArray arrayWithObjects:@"FirstName", @"LastName",@"UserName", @"Password",@"Email", @"Gender",@"DeviceId", @"DeviceName",@"ProfileImage", nil];

    NSData *_jsonData=nil;
    NSString *_jsonString=nil;
    NSURL *url=[NSURL URLWithString:urlstring];

    NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys];

    if([NSJSONSerialization isValidJSONObject:JsonDictionary]){
        _jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil];
        _jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
//    [request setHTTPBody:_jsonData];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [request setValue:[NSString stringWithFormat:@"%d", [_jsonData length]] forHTTPHeaderField:@"Content-Length"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    [request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];

    //    //return and test
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

请检查。

【问题讨论】:

    标签: ios json web-services post


    【解决方案1】:

    请求应该是这样的......

    NSURL * url = [NSURL URLWithString:@"your_url"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSError * error = nil;
    NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error];
    [request setHTTPBody:postData];
    

    我还建议检查您的回复,找出您的请求失败的原因。它是在客户端还是服务器端(为什么?)...

    【讨论】:

    • 当我提交到服务器时,在它显示的服务器上,它缺少'{'和'}'。
    • @Mithuzz 因为您没有提供有关后端基础架构的任何信息,所以无法提供更多帮助。请求到达服务器的事实更多地表明那里有问题,而不是客户端。
    • 为了清楚起见,在您的代码中,您没有为 NSJSONSerialization 设置选项,您纠正了吗?
    • 我们尝试从安卓设备发布到同一台服务器,它工作正常。在服务器上,我们使用 WCF Rest 服务,并使用反序列化。
    【解决方案2】:

    这是我尝试注册用户的示例代码。 在“注册”按钮点击,编写以下代码:

      - (IBAction)registerButtonPressed:(id)sender
    {
      BOOL valid = FALSE;
      valid=[self validateEntry];
      if(valid)
      {
        NSString *bytes = [NSString stringWithFormat:@"{\"UserName\":\"%@ %@\",\"Email\":\"%@\",\"UserType\":\"normaluser\",\"Password\":\"%@\"}",firstName,lastName,email,password];
        NSURL *url=[NSURL URLWithString:urlstring];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]];        
        [self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]];
        [self setResponseData:[NSMutableData data]];
        [self.urlConnection start];
      }
    }
    

    然后添加以下内容作为连接委托方法:

       - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse   *)response
    {
      [self.responseData setLength:0];
    }
    
    - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {    
      [self.responseData appendData:data];
    }
    - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Status"
                                                    message:@"Sorry,Network is not  available. Please try again later."
                                                   delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
       [alert show];
    
    }
    - (void) connectionDidFinishLoading:(NSURLConnection *)connection
    {
      if (connection == self.urlConnection) 
      {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;        
        NSError *error;        
        NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];        
        if(jsonString != nil)
        {          
            if ([[[jsonString objectForKey:@"data"] objectForKey:@"id"] length])
            {
                [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"id"] forKey:@"user_id"];
                [[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:@"data"] objectForKey:@"UserName"] forKey:@"user_name"];                
                [[NSUserDefaults standardUserDefaults] synchronize];
                [delegate userRegistrationViewControllerResponse:self];
            }
            else
            {
                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Info" message:[jsonString objectForKey:@"statusText"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [alertView show];
            }
        }
        else
        {
            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"Server Busy" message:@"Register after sometime" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alertView show];
        }
      }
    }
    
    • 这会将用户信息发布为 JSON。

    【讨论】:

      【解决方案3】:

      试试这个....

       NSURL *aUrl = [NSURL URLWithString:@"https://www.website.com/_api/Login/"];
       NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                               timeoutInterval:0.0];
       [request setHTTPMethod:@"POST"];
       NSString *postString = [NSString stringWithFormat:@"EmailAddress=%@&UserPassword=%@",uName.text,pwd.text];
       [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
       [[NSURLConnection alloc] initWithRequest:request delegate:self];
      

      -比调用 NSURLConnection 委托方法.. dot 忘了分配 responseData....

       - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
       [responseData appendData:data];
       }
      
       - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
       [connection release];
       NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
       responseData = nil;
       json =[[responseString JSONValue] retain];
       NSLog(@"Dict here: %@", json); 
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-29
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        相关资源
        最近更新 更多