如何在iPhone的Post方法中发送JSON请求?

时间:2011-11-18 11:52:06

标签: iphone json web-services request

我使用JSON字符串作为对服务器的请求,并以JSON格式获取响应。我已使用此代码发布数据

NSString *requestString = [NSString stringWithFormat:@"{\"id\":\"1\"}}"];
NSLog(@"the request string is %@", requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http//www.aaaa.com"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];

if( theConnection ){            
    receiveData = [[NSMutableData data] retain];
}  

在服务器端,他们使用核心PHP和post方法,每当我将请求发送到服务器时,我都没有得到数据,而JSON请求文件没有到达服务器。所以请帮帮我。

但是上面的代码在另一个项目中运行得很好,他们在服务器端使用了SOAP。所以请建议我,在服务器端或iPhone端,我可以在哪里更改代码来实现这一点。

谢谢!

4 个答案:

答案 0 :(得分:1)

除了Snips评论,

请同时添加以下标题。

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

另外,在这一行中,

NSString *requestString = [NSString stringWithFormat:@"{\"id\":\"1\"}}"];
它有两个紧密的括号。请检查一下。

<强>更新

您是否实施了NSURLConnectionDelegate方法?

请参阅link

答案 1 :(得分:0)

嗨,请在您的代码中添加以下行.....可能会帮助您

  

[request setValue:@“application / json”forHTTPHeaderField:@“Accept”];

答案 2 :(得分:0)

使用此代码

  • 使用需要的值创建post参数。
  • 在.h文件中实现NSURLConnectionDelegate委托。

          url=[NSURL URLWithString:@"#####called url ####### change this according your need ####"];
            post = [NSString stringWithFormat:@"name=%@&tags=%@&location=%@&location_lat=%f&location_lng=%f&pluses=%@&minuses=%@&image=%@&creator=%@",self.txtName.text,tags,self.txtLocation.text,center.latitude,center.longitude,plusValu,minusValu,imgUrlStr,deviceId];
    
         NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
    
        if(connection){
            resData = [NSMutableData data];
    
        }
    

    实现委托方法并从服务器获取数据

      (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
      {
       NSLog(@"didReceiveResponse %s##### response  %@",__FUNCTION__,response);
     //[resData setLength:0];
      }
    
     (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
       {
       NSLog(@"didReceiveData %@",[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] JSONValue]);
    
      }
    
       (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
          {
         //NSLog(@"didFailWithError %s and Error %@",__FUNCTION__,[error userInfo]);
       //[responseData release];
        // [_delegate parserDidFailedWithError:[NSString stringWithFormat:@"Connection failed:  %@",   [error description]] forAction:_action];
        }
    
     (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    
       //   NSLog(@"connectionDidFinishLoading %s",__FUNCTION__);
    
    }
    

答案 3 :(得分:0)

您需要以下内容:

NSDictionary *dataDict = @{@"id": @"1"};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http//www.aaaa.com"]];

[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

if ( theConnection ) {            
    receiveData = [[NSMutableData data] retain];
}