有没有办法将参数的NSDictionary附加到NSURLRequest而不是手动创建字符串?

16 objective-c nsurlconnection nsurlrequest ios nsurlsession

AFNetworking允许您向NSDictionary请求添加一个参数,它会将它们附加到请求中.因此,如果我想做一个GET请求,?q=8&home=8888我只是@{@"q": @"8", @"home": @"8888"}简单地制作一个NSDictionary .

是否有办法用NSURLSession/ NSURLConnection/ NSURLRequest

我知道我可以NSJSONSerialization用来附加JSON数据,但如果我只想将它们作为GETURL中的参数呢?我应该添加一个类别吗?

Pet*_*ese 10

您可以使用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;
Run Code Online (Sandbox Code Playgroud)


bha*_*ari -1

尝试下面的工作代码

// 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];
Run Code Online (Sandbox Code Playgroud)

  • 这适用于 POST 请求,不适用于 GET 请求,其中参数必须在 url 中进行 url 编码(与 post 的 http 主体上的数据相反) (2认同)