Skip to content

Instantly share code, notes, and snippets.

@krhoyt
Last active December 27, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krhoyt/7359194 to your computer and use it in GitHub Desktop.
Save krhoyt/7359194 to your computer and use it in GitHub Desktop.
Send an HTTP GET request with query string values.
- ( NSString * ) encodeDictionary : ( NSDictionary * ) parameters
{
NSMutableString * query;
query = [[NSMutableString alloc] init];
[parameters enumerateKeysAndObjectsUsingBlock : ^( id key, id value, BOOL *stop ) {
[query appendFormat : @"%@=%@&", key, value];
}];
return [query substringToIndex : ( [query length] - 1 )];
}
- ( NSString * ) loadFileHTTPGetQueryString : ( NSString * ) url withQueryStringParameters : ( NSDictionary * ) parameters
{
NSData * get;
NSError * error;
NSHTTPURLResponse * response;
NSMutableString * location;
NSMutableURLRequest * request;
NSString * contents;
NSString * query;
// Form query string
query = [self encodeDictionary : parameters];
NSLog( @"%@", query );
location = [[NSMutableString alloc] init];
[location appendFormat : @"%@?%@", url, query];
NSLog( @"%@", location );
// Load a file over HTTP GET
request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod : @"GET"];
[request setURL:[NSURL URLWithString : location]];
error = [[NSError alloc] init];
response = nil;
get = [NSURLConnection sendSynchronousRequest : request returningResponse : &response error : &error];
if( [response statusCode] != 200 )
{
NSLog( @"Error making HTTP request: %@", error );
} else {
contents = [[NSString alloc] initWithData : get encoding:NSUTF8StringEncoding];
NSLog( @"Query string response: %@", contents );
}
return contents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment