在iOS上使用POST params的HTTPRequest

时间:2012-07-17 20:43:54

标签: ios ios5 httprequest

我尝试按照此帖iOS: how to perform a HTTP POST request?中的说明操作,但不幸的是服务器回答但没有给我任何数据。

调用connection didReceiveResponse以及connectionDidFinishLoading没有错误。

我做错了吗?我使用Hurl.it对服务进行了测试,结果恰到好处。

requestUrlString =正常网址,

postString =类似“appId = 1& last_update = 0”

responseData = [[NSMutableData alloc] initWithLength:0];

NSURL *baseURL = [NSURL URLWithString:[requestUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:baseURL];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d",[postString length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection start];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
    NSLog(@"Connection didReceiveResponse");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    NSLog(@"Connection didReceiveData");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection Error: %@", [error description]);

    [[[UIAlertView alloc] initWithTitle:@"Error"
                                 message:[error description]
                                delegate:nil
                       cancelButtonTitle:@"OK"
                       otherButtonTitles:nil] show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Connection didFinishLoading");
    NSLog(@"data %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}

请不要参考我在这里得到的ASIHTTP。

//编辑:我很抱歉打扰了你的问题。问题是编码类型。

1 个答案:

答案 0 :(得分:0)

Web服务是否生成响应正文? 或者只是生成响应头?如果没有响应正文,则无法在iOS上显示响应。

另外,我相信你需要一个“接受”标题。