GET请求使用太多参数 - iOS

时间:2013-12-18 18:09:01

标签: ios http get

我正在尝试在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

的当前输出为null

1 个答案:

答案 0 :(得分:4)

在我看来,问题在于您使用某种编码方法对整个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];