iPhone アプリケーションから POST または GET リクエストを送信できますか? 質問する

iPhone アプリケーションから POST または GET リクエストを送信できますか? 質問する

iPhone SDK を使用して HTTP POST または GET メソッドと同じ結果を得る方法はありますか?

ベストアンサー1

クラスにresponseDataインスタンス変数があると仮定すると、次のようになります。

responseData = [[NSMutableData data] retain];

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

次に、クラスに次のメソッドを追加します。

- (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
}

これにより、GET が送信されます。最終メソッドが呼び出されるまでに、responseDataHTTP 応答全体が含まれます ([[NSString alloc] initWithData:encoding:] を使用して文字列に変換されます)。

あるいは、POST の場合は、最初のコード ブロックを次のように置き換えます。

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

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

おすすめ記事