16

AFNetworking allows you to add an NSDictionary of parameters to a request, and it will append them to the request. So if I wanted to do a GET request with ?q=8&home=8888 I'd just making an NSDictionary like @{@"q": @"8", @"home": @"8888"} very simply.

Is there a way to do this with NSURLSession / NSURLConnection / NSURLRequest?

I know I can use NSJSONSerialization for appending JSON data, but what if I just want them as GET parameters in the URL? Should I just add a category?

SamB
  • 9,039
  • 5
  • 49
  • 56
  • check i have just posted answer - its pretty simple with NSMutableURLRequest – bhavya kothari Jan 23 '14 at 05:14
  • possible duplicate of [Creating URL query parameters from NSDictionary objects in ObjectiveC](http://stackoverflow.com/questions/718429/creating-url-query-parameters-from-nsdictionary-objects-in-objectivec) – Pochi Jul 10 '14 at 02:28

3 Answers3

10

You can do this by updating the url using NSURLComponents and NSURLQueryItems. In the following example, assume that the URL parameter has already been set on an NSMutableURLRequest. You can modify it before using it to include each parameter from the NSDictionary params. Note that each parameter is encoded before it is written.

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;
Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
-1

TRY BELOW WORKING CODE

// 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];
bhavya kothari
  • 7,484
  • 4
  • 27
  • 53
  • 2
    This is for a POST request, not for a GET request in where the parameters must be url encoded in the url (contrary to as data on the http body for post) – Pochi Jul 10 '14 at 02:26
  • Actually, this is working for me as I'm searching for POST request. Thanks. – Chen Li Yong Nov 25 '16 at 04:31
-2

Example using 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];
Xuan
  • 460
  • 5
  • 13