How to Make Post Nsurlrequest with 2 Parameters

How to make POST NSURLRequest with 2 parameters?

It will probably be easier to do if you use AFNetworking. If you have some desire to do it yourself, you can use NSURLSession, but you have to write more code.

  1. If you use AFNetworking, it takes care of all of this gory details of serializing the request, differentiating between success and errors, etc.:

    NSDictionary *params = @{@"firstname": @"John", @"lastname": @"Doe"};

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"responseObject = %@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"error = %@", error);
    }];

    This assumes that the response from the server is JSON. If not (e.g. if plain text or HTML), you might precede the POST with:

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  2. If doing it yourself with NSURLSession, you might construct the request like so:

    NSDictionary *params = @{@"firstname": @"John", @"lastname": @"Doe"};

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self httpBodyForParameters:params]];

    You now can initiate the request with NSURLSession. For example, you might do:

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
    NSLog(@"dataTaskWithRequest error: %@", error);
    }

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
    NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
    if (statusCode != 200) {
    NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);
    }
    }

    // If response was JSON (hopefully you designed web service that returns JSON!),
    // you might parse it like so:
    //
    // NSError *parseError;
    // id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    // if (!responseObject) {
    // NSLog(@"JSON parse error: %@", parseError);
    // } else {
    // NSLog(@"responseObject = %@", responseObject);
    // }

    // if response was text/html, you might convert it to a string like so:
    //
    // NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // NSLog(@"responseString = %@", responseString);
    }];
    [task resume];

    Where

    /** Build the body of a `application/x-www-form-urlencoded` request from a dictionary of keys and string values

    @param parameters The dictionary of parameters.
    @return The `application/x-www-form-urlencoded` body of the form `key1=value1&key2=value2`
    */
    - (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
    NSMutableArray *parameterArray = [NSMutableArray array];

    [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
    NSString *param = [NSString stringWithFormat:@"%@=%@", [self percentEscapeString:key], [self percentEscapeString:obj]];
    [parameterArray addObject:param];
    }];

    NSString *string = [parameterArray componentsJoinedByString:@"&"];

    return [string dataUsingEncoding:NSUTF8StringEncoding];
    }

    and

    /** Percent escapes values to be added to a URL query as specified in RFC 3986.

    See http://www.ietf.org/rfc/rfc3986.txt

    @param string The string to be escaped.
    @return The escaped string.
    */
    - (NSString *)percentEscapeString:(NSString *)string {
    NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
    return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    }

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];

Simply append your key/value pair to the post string

NSURLRequest with multiple parameters

I always create a new data structure,which has a -connection property and a -request property,like this

@interface connectionWrapper : NSObject
@property(retain) NSURLRequest *request
@property(retain) NSURLConnection *connection

by retaining this data structure in an mutable array, you can distinguish the connections in callback methods by iterate the array and compare each connectionWrapper instance's -connection property with the connection parameter the of the callback method, if they match(points to a same object), then you can retrieve the -request property of the connectionWrapper instance, then -url property of NSURLRequest instance.

as I'm not an native English speaker, I think code is a better tutor.

-(NSURLRequest*)getRequestByConnection:(NSURLConnection*)connection
{
for(connectionWrapper *w in theArrayContainingAllConnectionWrappers)
{
if(w == connection)
return w.request;
}
}

In callback method:

-(void)connection:(NSURLConnection*)connection didReceiveResponse(NSURLResponse*)response
{
NSURLRequest *request = [self getRequestByConnection:connection];
NSURL *url = [request url];
/*apply different approach to different url/*
}

PS:it's very sad that NSURLConnection don't have a -request property so that we can retrieve the request associated with the connection easily.

Get POST parameter from NSURLRequest

That should be possible with the class method of NSURLProtocol:

+ (id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request

So if you have got a property named "place" you could try that:

[NSURLProtocol propertyForKey:@"place" inRequest:myRequestObject]

[EDIT]
If you want to retrieve all properties, I think you have to use - (NSData *)HTTPBody
from NSURLRequest and then parse the property names/values yourself. Should be no problem with urldecode and RegEx.

How can pass multiple parameters in NSURL string in iOS?

try creating a separate string before adding to the URL something like

 NSSString *strURL=[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@"‌​,strfrom,strto,strgo];

and then add this strURL to URL

NSURL *url = [NSURL URLWithString:strURL];

finally add it to the request, your code is wrong where you adding url to request, URL is not a string it is a URL so it should be requestWithURL not URLWithString, it should be like this

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLRequest : Post data and read the posted page

A few things first

  • Decide how you want to encode your data - JSON or url-encoding are a good start.
  • Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
  • Read up on the URL Loading System, it's your friend.

Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions will need to be saved to ivars or in your request's userInfo dict.

Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.

Without further ado, here's a quick and dirty url-encoder:

- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}

Using a JSON library like JSONKit makes encoding things easier, consider it!

Method 1 - NSURLConnectionDelegate async callbacks:

// .h
@interface ViewController : UIViewController<NSURLConnectionDelegate>
@end

// .m
@interface ViewController () {
NSMutableData *receivedData_;
}
@end

...

- (IBAction)asyncButtonPushed:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://localhost/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username",
@"password", @"password", nil];
NSData *postData = [self encodeDictionary:postDict];

// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];

[connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData_ setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData_ appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %d bytes of data", [receivedData_ length]);
NSString *responeString = [[NSString alloc] initWithData:receivedData_
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:@"true"]) {
// Deal with true
return;
}
// Deal with an error
}

Method 2 - Grand Central Dispatch async function:

// .m
- (IBAction)dispatchButtonPushed:(id)sender {

NSURL *url = [NSURL URLWithString:@"http://www.apple.com/"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username",
@"password", @"password", nil];
NSData *postData = [self encodeDictionary:postDict];

// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
// Deal with your error
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(@"HTTP Error: %d %@", httpResponse.statusCode, error);
return;
}
NSLog(@"Error %@", error);
return;
}

NSString *responeString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
// Assume lowercase
if ([responeString isEqualToString:@"true"]) {
// Deal with true
return;
}
// Deal with an error

// When dealing with UI updates, they must be run on the main queue, ie:
// dispatch_async(dispatch_get_main_queue(), ^(void){
//
// });
});
}

Method 3 - Use an NSURLConnection convenience function

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

Hope this helps.

Alamofire NSURLRequest via POST method doesn't work

I've checked your code and before executing encode function your request.HTTPBody is empty, but after it has some data like

Optional<NSData>
- Some:<7b22546f 6b656e22 3a22736f 6d657468 696e6722 2c224964 223a2231 32333435 3637227d>

When I call print(response.request?.HTTPBody) in Alamofire response block, I get the parameters as NSData and the HTTPBody includes the same data as before sending the request so it works.

Try also change the response from responseJSON to responseString, because if your response can't be parsed to JSON you get Failure.

I think you should check on your URL site if you get correct data.

Instead of your solution I use

Alamofire.request(method, url, parameters: parameters, encoding: .JSON) .responseString{ response in}

is the same but shorter and everything is as parameters.



Related Topics



Leave a reply



Submit