Search code examples
objective-curlafnetworkingafhttpclient

NSURL going wrong


I have URL like this for example:

http://somedomain.com/mi3/marketInfoData?request=login&user=user&password=password

but why URL string not same with that I want... it return

http://somedomain.com/mi3/marketInfoData/?request=login&user=user&password=pass

here my NSurl request

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://somedomain.com/mi3/marketInfoData?request=login&user=user&password=pass"]];

Error:

AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest http://somedomain.com/mi3/marketInfoData/?request=login&user=user&password=pass <--error

and I got an error like this because it has "/" before "?" How do I escape it?


Solution

  • From the documentation:

    Also important to note is that a trailing slash will be added to any baseURL without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.

    Try this pattern:

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://somedomain.com/mi3/"]];
    
    NSDictionary *params = @{@"request": @"login", @"user" : @"user", @"password" : @"pass"};
    
    [httpClient getPath:@"marketInfoData" parameters:params success:nil failure:nil];
    

    Obviously, you don't really want to use nil success and failure blocks.

    You should typically create one AFHTTPClient for each API you're hitting (most apps only have one.) Creating a new AFHTTPClient for each request is an error.