有没有办法将参数的NSDictionary附加到NSURLRequest而不是手动创build一个string?

AFNetworking允许你添加一个参数的NSDictionary到一个请求,并将它附加到请求。 所以,如果我想要做一个GET请求?q=8&home=8888我只是简单地做一个NSDictionary,比如@{@"q": @"8", @"home": @"8888"}

有没有办法做到NSURLSession / NSURLConnection / NSURLRequest

我知道我可以使用NSJSONSerialization来附加JSON数据,但是如果我只是希望它们作为GET参数在URL中呢? 我应该只是添加一个类别?

你可以通过使用NSURLComponents和NSURLQueryItems来更新URL。 在以下示例中,假设已经在NSMutableURLRequest上设置了URL参数。 您可以在使用它来包含NSDictionary params每个参数之前对其进行修改。 请注意,每个参数在写入之前都进行了编码。

 NSURLComponents *url = [[NSURLComponents alloc] initWithURL:request.URL resolvingAgainstBaseURL:YES]; NSMutableArray *queryItems = NSMutableArray.new; [params enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) { [queryItems addObject:[NSURLQueryItem queryItemWithName:name value:[value stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]]]; }]; url.queryItems = queryItems; request.URL = url.URL; 

尝试下面的工作代码

 // Create the request. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"YOUR URL"]]; // Specify that it will be a POST request request.HTTPMethod = @"POST"; // This is how we set header fields [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; // Convert your data and set your request's HTTPBody property NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"44",@"UserId",@"0",@"NewsArticleId",@"",@"Date", nil]; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; request.HTTPBody = jsonData; // Create url connection and fire request NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

使用NSURLSession的示例:

 NSURLSession *session = [NSURLSession sharedSession]; //populate json NSDictionary *gistDict = @{@"files":@"test",@"description":@"test"}; NSError *jsonError; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gistDict options:NSJSONWritingPrettyPrinted error:&jsonError]; //populate the json data in the setHTTPBody:jsonData NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://yourURL"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:jsonData]; //Send data with the request that contains the json data [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Do your stuff... }] resume];