ASIHTTPRequest appendPostData无法正常工作

时间:2012-04-12 07:41:06

标签: iphone post asihttprequest

我想使用ASIHTTPRequest appendPostData方法将字符串数据发送到php服务器,但它无效。

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startAsynchronous];

我尝试对请求本身进行一些修改,如:

[request setRequestMethod:@"POST"];
[request buildPostBody];

但这也行不通。

当我使用

[request addPostValue:@"Ben" forKey:@"names"];

语法确实有效。

有人知道这里有什么问题吗?!

1 个答案:

答案 0 :(得分:1)

我通常使用它:

- (void)performPostRequestWithString:(NSString *)string stringDictionary:(NSDictionary *)stringDictionary dataDictionary:(NSDictionary *)dataDictionary delegate:(id)requestDelegate requestSelector:(SEL)requestSelector errorSelector:(SEL)errorSelector {

    //localCopy = self;

    self.delegate = requestDelegate;
    self.callback = requestSelector;
    self.errorCallback = errorSelector;

    NSURL *url = [NSURL URLWithString:string];

    postRequest = [[ASIFormDataRequest alloc] initWithURL:url];
    [postRequest setDelegate:self];
    [postRequest setRequestMethod:@"POST"];

    if (stringDictionary)
        for (NSString *key in [stringDictionary allKeys])
            [postRequest setPostValue:[stringDictionary objectForKey:key] forKey:key];

    if (dataDictionary)
        for (NSString *key in [dataDictionary allKeys])
            [postRequest setData:[dataDictionary objectForKey:key] forKey:key];

    //NSLog(@"request url = %@", [postRequest.url absoluteString]);
    [postRequest startAsynchronous];
}

参数:

  • (NSString *)string - url字符串,发布请求的位置;
  • (NSDictionary *)stringDictionary - 字典,包含所有文本信息(例如名称,ID等);
  • (NSDictionary *)dataDictionary - 字典,包含所有数据信息(如照片,文件等);
  • (id)requestDelegate - 委托执行以下选择器;
  • (SEL)requestSelector - 选择器,将在成功请求时执行;
  • (SEL)errorSelector - 选择器,会在发生错误时执行。

P.S。选择器将用于ASIHTTPRequest Delegate实现