URL GET / POST请求目标-c

时间:2010-01-07 08:42:43

标签: objective-c url post get request

我必须向localhost发送get或post请求:

<?php
 if(@$_GET['option']) {
  echo "You said \"{$_GET['option']}\"";
 }else if(@$_POST['option']) {
  echo "You said \"{$_POST['option']}\"";
 }
?>

我使用此代码:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/wsh/index.php?option=Hello"]];
 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
 NSString *get = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

它有效,但在代码中有一次。如果生病再做一次,申请已经终止。

我尝试使用ASIFormDataRequest:

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:@"http://localhost/wsh/index.php"] autorelease];
[request setPostValue:@"option" forKey:@"myFormField1"];
[request start];
NSError *error = [request error];
if (!error) {
  NSString *response = [request responseString];
  NSLog(response);
}else{
  NSLog(@"error");
}

它说:

2010-01-07 13:20:34.964 WSH[3351:903] -[NSCFString absoluteURL]: unrecognized selector sent to instance 0x160f8
2010-01-07 13:20:34.966 WSH[3351:903] error

sry for my english

2 个答案:

答案 0 :(得分:8)

您使用的是纯文本NSString字面值,其中需要NSURL个对象:[...] initWithURL:@"http://localhost/wsh/index.php" [...]

将其更改为initWithURL:[NSURL URLWithString:@"http://localhost/wsh/index.php"]

答案 1 :(得分:6)

我想知道你是否也应该为post值切换值和键,即改变行

[request setPostValue:@"option" forKey:@"myFormField1"];

[request setPostValue:@"myFormField1" forKey:@"option"];