Is there any way to attach a NSDictionary of parameters to an NSURLRequest instead of manually making a string?

守給你的承諾、 提交于 2019-11-28 07:02:56

问题


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?


回答1:


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;



回答2:


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];



回答3:


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];


来源:https://stackoverflow.com/questions/21299362/is-there-any-way-to-attach-a-nsdictionary-of-parameters-to-an-nsurlrequest-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!