更新:次のようにPOSTの場合、あなたはそれを変更したい をので、[NSURLConnection sendSynchronousRequest]
はiOSの9から始まる廃止されました。ここのiOS 9
から始まる
NSURLSession
を使用してGET要求を行う方法です
GETリクエスト
// making a GET request to /init
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data received: %@", myString);
}] resume];
POSTリクエスト
// making a POST request to /init
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Make an NSDictionary that would be converted to an NSData object sent over as JSON with the request body
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
@"basic_attribution", @"scenario_type",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data received: %@", responseStr);
}] resume];
クイックレスポンスに感謝します。私はちょうどこれがどんなデータをどのように正確に渡すかに関してちょっと混乱していますか?単にHTTPサービスに接続する機能のようですか? –
POSTサンプルは '[setHTTPBody:body]'行を介してデータを渡し、HTTP本体に到着します。 GETの例ではURLのデータが渡されるため、URLのフォーマットを事前に行う必要があります。おそらく '[NSString stringWithFormat:@" http://example.com?param1=%@¶m2=%@ "、param1、param2]'。 –
これは、ページソースと同じNSLOGに "が登録 "を返しています。実際のページは登録されたまま出力されています。私は他のすべてを解析できるという意味での些細な違いだと思いますが、このコードは適切な出力ではなくページデータを返していますか? –