简体   繁体   中英

AFNetworking building a URL for GET with parameters

I have a few paramaters I want to pass to the URL when performing a GET

The method I use for building the URL is:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: baseURL];

NSString* url = @"http://pretendurl.com/something";

NSMutableURLRequest *request = [httpClient requestWithMethod: @"GET"
                                                        path: url
                                                  parameters: params];

Where params is an nsdictionary that has been populated.

This adds the parameters to the url file but it adds &format=json to the end of the URL.

I would like to know how to get it to build the URL without the last piece. I had a look through the AFNetworking source code but couldn't spot where it actually adds that bit.

Thanks in advance.

you could convert you dictionary params to query url using a function like this

-(NSString*) getQueryUrlFromDictionary:(NSDictionary*) dict usingUrlEncoder:(BOOL)makeUrlEncoded
{
    if (dict == nil)
        return @"";

    NSMutableString* outputStr = [[NSMutableString alloc] initWithString:@""];
    int px = 0;
    for (NSString* key in dict) {

        NSString* param = (NSString*) [dict objectForKey:key];
        // using urlEncoding : look for NSString+URLEncoding.h implementation
        if (makeUrlEncoded)
            param = [param urlEncodeUsingEncoding:NSUTF8StringEncoding];

        [outputStr appendFormat:@"%@=%@",key,param];
        if ( px < ([dict count]-1 ) )
            [outputStr appendString:@"&"];

        px++;
    }

    return outputStr;
}

So ...

NSMutableURLRequest *request = [NSMutableURLRequest
                                  requestWithURL: baseURL
                                  cachePolicy: NSURLRequestReloadIgnoringLocalCacheData 
                                  timeoutInterval: 60.f];

[request setHTTPMethod:@"GET"];


NSString* paramString = [self getQueryUrlFromDictionary:params usingUrlEncoder:YES];

NSData *postData = [paramString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

[request setHTTPBody:postData];

I use something like this and works fine, hope it helps

for me everything should work fine, but try this:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:"http://pretendurl.com"]];

 NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                                path:@"something"
                                                          parameters:params];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM