我尝试按照这篇iOS 帖子中的说明进行操作:如何执行 HTTP POST 请求?但不幸的是,服务器回答但没有给我任何数据。
被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 我在这里得到了同样的结果。
//编辑:我修复了很抱歉打扰你我的问题。问题是编码类型。