使用Objective C创建JSON数据并将其发送到服务器

时间:2015-09-24 09:39:05

标签: ios objective-c json xcode

我尝试使用POST方法将JSON数据发送到服务器端,但我的代码提供了空JSON值。我正在使用Objective C,我从textField获取数据并将其转换为字符串,但在此之后将此值转换为JSON对象时,它会给出null值。不知道该怎么做。

这是我的代码:

- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}

4 个答案:

答案 0 :(得分:1)

-(void)MessagePost{
NSString * post =[NSString stringWithFormat:@"http://url.com/clients/project_id=%@&user_id=58&question=%@&send_enquiry=Send",[[self.recordchat objectForKey:@"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(@"String : %@",returnstring);
if (postdata){
    NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
    NSDictionary* latestLoans = [dict objectForKey:@"status"];
    NSLog(@"Status dict = %@",latestLoans);
}  else{ NSLog(@"Error while posting messages.");}}

答案 1 :(得分:0)

instead of writing NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
 you should use this
    NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
    [post setValue:self.userNameField.text forKey:@"Username"];
    [post setValue:self.passwordField.text forKey:@"Password"];

答案 2 :(得分:0)

试试这个 -

- (IBAction)loginAction:(UIButton *)sender
 {
   NSDictionary *dictDetails = @{
                          @"Username" : self.userNameField.text,
                          @"Password" : self.passwordField.text
                          };

   NSString *jsonRequest = [dict JSONRepresentation];
   NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]];

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

   NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

  [request setHTTPMethod:@"POST"];
  [request setHTTPBody: requestData];
  [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)   
  [requestData length]] forHTTPHeaderField:@"Content-Length"];

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

  NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [theConnection start];

  NSError *error = [[NSError alloc] init];
  NSHTTPURLResponse *response = nil;
  NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}

答案 3 :(得分:0)

最后我写了正确的代码,现在工作正常。请建议我如果需要进一步修改.. 谢谢大家的时间和支持.. 这是我的代码:

- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:@"username"];
[post setValue:self.passwordField.text forKey:@"password"];


    NSArray* notifications = [NSArray arrayWithObjects:post, nil];
    NSError *writeError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
    NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
   [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login"]]];
   [request setHTTPMethod:@"POST"];
   [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
   [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   [request setHTTPBody:jsonData];
   NSLog(@"JSON Summary: %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
   NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   [theConnection start];

   NSError *error = [[NSError alloc] init];
   NSHTTPURLResponse *response = nil;
   NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   NSLog(@"Response Error= %@", response);

    if ([response statusCode] >=200 && [response statusCode] <300)
    {

    NSData *responseData = [[NSData alloc]initWithData:urlData];
    NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Random Output= %@", jsonObject);
    [self performSegueWithIdentifier:@"DASHBOARDSEGUE" sender:sender];
    }else {
    [self alertStatus:@"Connection Failed" :@"Login Failed!"];
    }

}