OStack程序员社区-中国程序员成长平台

标题: ios - GET 请求使用了太多参数 - iOS [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:45
标题: ios - GET 请求使用了太多参数 - iOS

我正在尝试在 NSMutableURLRequest 中为 GET 请求加载 URL,如下所示:

 NSString *serverAddress =  [NSString stringWithFormat"http://test.us.to:8080/api/offers?altId=%@&provider=%@&otherId=%@&tenantId=%@&createdAt=%@&otherOfferId=%@&postId=%@&pageId=%@&sourceUrl=%@&name=%@&description=%@&text=%@&category=%@&caption=%@&startTime=%@&expirationTime=%@&minPurchase=%@&numPurchases=%@&value=%@&percent=%@&count=%@&currency=%@&terms=%@&campaignId=%@&partnerId=%@&tenantIdAtPartner=%@&issuerName=%@&claimLimit=%@&onePerUser=%@&emailTemplateFile=%@",@"test",@"Facebook",@"",@"test",@"null",@"test",@"",@"",@"http://test.us.to/offers/harvester_summer13.html",@"Harvester",@"Harvester 2for1 TakeAway",@"Enjoy!",@"voucher",@"Harvester 2for1 TakeAway",[NSNumber numberWithInt:0],@"test",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],@"1000",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],@"GBP",@"",[NSNumber numberWithInt:1259],@"null" ,@"null" ,@"null",[NSNumber numberWithInt:100],[NSNumber numberWithBool:false],@"templates/test.vm"];

 NSURL *url = [NSURL URLWithString:[serverAddress urlEncodeUsingEncoding:NSUTF8StringEncoding]];

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15.0];

 NSString *authStr = [NSString stringWithFormat"%@:%@", @"testuser", @"testpwd"];
 NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
 NSString *authValue = [NSString stringWithFormat"Basic %@", [authData base64EncodedStringWithOptions:0]];
 [request setValue:authValue forHTTPHeaderField"Authorization"];



 [request setHTTPMethod: @"GET"];

 NSError *requestError;
 NSURLResponse *urlResponse = nil;

 NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];

NSLog(@"输出数据%@",response1);

我想我使用 url 字符串加载了太多参数。有没有更好的方法来为 GET 请求传递参数? response1 的当前输出为空



Best Answer-推荐答案


在我看来,问题在于您正在使用某种编码方法对整个 url 进行编码,但如果每个参数包含某些字符,您实际上只需要单独编码。例如:

NSString *serverAddress = @"http://test.us.to:8080/api/offers";

NSString *altIdParameter = [@"Escape?This?String?" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *aUrlParameter = [@"http://test.us.to/offers/harvester_summer13.html" urlEncodeUsingEncoding:NSUTF8StringEncoding];

NSString *getRequestUrl = [NSString stringWithFormat:%@?altId=%@&urlParam=%@", serverAddress, altIdParameter, aUrlParameter];

NSURL *url = [NSURL URLWithString:getRequestUrl];

关于ios - GET 请求使用了太多参数 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20665349/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4