Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

objective c - Can I make POST or GET requests from an iphone application?

Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assume your class has a responseData instance variable, then:

responseData = [[NSMutableData data] retain];

NSURLRequest *request =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

And then add the following methods to your class:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // Show error
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Once this method is invoked, "responseData" contains the complete result
}

This will send a GET. By the time the final method is called, responseData will contain the entire HTTP response (convert to string with [[NSString alloc] initWithData:encoding:].

Alternately, for POST, replace the first block of code with:

NSMutableURLRequest *request =
        [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[request setHTTPMethod:@"POST"];

NSString *postString = @"Some post string";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...