Objective C HTTP Post Request参数在App和Server之间丢失

时间:2013-04-01 00:48:18

标签: objective-c xcode post

我正在尝试从我的iOS应用程序向服务器发送帖子请求。使用curl时请求有效:

curl -d "uid=1&type=robbery&x=41.66505&y=-93.73046" http://thawing-ravine-5632.herokuapp.com/sos

这是发出请求的Objective-C代码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL
                                                 URLWithString:@"http://thawing-ravine-5632.herokuapp.com/sos"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:x
   forHTTPHeaderField:@"x"];
    [request setValue:y
   forHTTPHeaderField:@"y"];
    [request setValue:type
   forHTTPHeaderField:@"type"];
    [request setValue:uid
   forHTTPHeaderField:@"uid"];

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

最后,didReceiveData记录以下内容:

2013-03-31 20:29:32.248 THST Mobile[14720:11c03] connectionDidReceiveData {"student_found":0,"school_found":0,"officer_found":0,"text_sent":0,"uid":0,"x":0.0,"y":0.0,"type":null}

但是在发出请求之前记录变量表明它们确实在发出请求之前在应用程序中实例化了。 SSH服务器显示,收到请求时,它们只是nil或空字符串。因此,我的Objective-C代码发出post请求有问题 - 可能与我设置参数的方式有关吗?

1 个答案:

答案 0 :(得分:9)

您将值设置为标题,而不是请求的正文。

NSString *params = @"x=1&y=bla&z=foo";
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];