ASIHttpRequest POST

2019-08-11 13:49发布

I am working on an iphone app and my requirements are to make a simple post to a web service and the web service returns a json response.

The sample code they give for a post is this, but how do I get a response? I see there is asynchronous code for doing a get, but how do I do it async for a post?

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];

2条回答
Ridiculous、
2楼-- · 2019-08-11 14:22

This you use for posting a synchronous response, the response will be in the var "response".

- (IBAction)grabURL:(id)sender
{
  NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
  ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  [request startSynchronous];
  NSError *error = [request error];
  if (!error) {
    NSString *response = [request responseString];
  }
}

To make a async request, do the following:

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   // Use when fetching binary data
   NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error];
}

Basically the request finished will be called when there is data, depending on the format you can get either a NSData or a NSString like in the example.

Your params you can put in like you said yourself:

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

I have used a normal type of requesting, you could replace the ASIHTTPRequest class with ASIFormDataRequest.

查看更多
我只想做你的唯一
3楼-- · 2019-08-11 14:41

If you're targeting iOS 4+ you can use blocks, which makes asynchronous code a little bit nicer. You won't have to deal with delegates.

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];

[request setCompletionBlock:^{
    NSLog(@"%@", request.responseString);
}];

[request setFailedBlock:^{

    NSLog(@"%@", request.error);
}];

[request startAsynchronous];    

More about blocks http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

查看更多
登录 后发表回答