【发布时间】:2010-12-08 16:49:22
【问题描述】:
我正在构建一个 iPhone 客户端,它将 GET 和 POST 到 REST 服务。 GET 部分工作正常,但我似乎无法发布任何内容。服务器目前只接受 xml。 我尝试使用 ASIHTTPRequest、ASIFormDataRequest 并自己做,但似乎没有任何效果。 谁能帮我?我是 Objective-C 编程的新手。
我确实得到了一个状态代码:200 作为响应,在 didReceiveResponse 中使用以下代码:
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
int myStatus = httpResponse.statusCode;
if (myStatus == 400) {
NSLog(@"Status code: 400");
} else if (myStatus == 200) {
NSLog(@"Status code: 200");
} else {
NSLog(@"Other status code");
以下是三种不同的方法...
代码(ASIHTTPRequest):
NSURL *url = [NSURL URLWithString:@"myUrl.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"<my xml>" dataUsingEncoding:NSUTF8StringEncoding]];
// Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request startSynchronous];
代码(ASIFormDataRequest):
NSURL *url = [NSURL URLWithString:@"someUrl.com"];
ASIFormDataRequest *theRequest = [ASIFormDataRequest requestWithURL:url];
// [theRequest setPostValue:@"" forKey:@"key1"];
[theRequest setPostValue:@"90" forKey:@"key2"];
[theRequest setPostValue:@"150" forKey:@"key3"];
// [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
[theRequest startAsynchronous];
代码(第三种方法):
NSData *myPostData = [[NSString stringWithFormat:@"<my xml>"] dataUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding];
// NSString *xmlPostData = @"<my xml>";
NSURL *theURL = [NSURL URLWithString:@"someUrl.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-type"];
// [theRequest setValue:@"UTF-8" forHTTPHeaderField:@"Charset"];
[theRequest setHTTPBody:myPostData];// [xmlPostData dataUsingEncoding:NSUTF8StringEncoding]];// myPostData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
所有这些 -(void)connection: 样式函数怎么样?它们中的任何一个都必须包含特定代码才能使连接正常工作吗?
非常感谢您的帮助!
【问题讨论】:
-
到底是什么问题?如果您收到 200,则服务器收到请求并做出响应。您是否缺少服务器或客户端上的行为?
-
您的宁静网络服务一切正常吗?因为 iphone 上的一切看起来都不错。
-
我现在真的让它工作了。我必须明确告诉 ASIHTTPRequest 我想要什么 Content-Type。以为它会自行解决这个问题,但没有......无论如何感谢你们的 cmets 家伙!工作代码如下。
标签: iphone objective-c rest post