How do you append data to an existing POST
NSURLRequest
? I need to add a new parameter userId=2323
.
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
initWithRequest
starts the request and returns the NSURLConnection
reference in case you need it (and you can check to see that it's non-nil
, to make sure the request started OK). –
Tetraploid NSURLConnectionDataDelegate
methods. And, of course, you should percent escape the values you insert into your HTTPBody
. –
Tetraploid All the changes to the NSMutableURLRequest
must be made before calling NSURLConnection
.
I see this problem as I copy and paste the code above and run TCPMon
and see the request is GET
instead of the expected POST
.
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];
The previous posts about forming POST
requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.
//create body of the request
NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData *postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//initialize a connection from request, any way you want to, e.g.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Where the precentEscapeString
method is defined as follows:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)@" ",
(CFStringRef)@":/?@!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
Note, there was a promising NSString
method, stringByAddingPercentEscapesUsingEncoding
(now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the +
or &
characters).
The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters
, but, again, don't be tempted to use URLQueryAllowedCharacterSet
, as that also allows +
and &
pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet
to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.
For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet
and then remove generalDelimitersToEncode
(which includes the characters #
, [
, ]
, and @
, but because of a historical bug in some old web servers, neither ?
nor /
) and subDelimitersToEncode
(i.e. !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, and =
). This is correct implementation (though you could debate the removal of ?
and /
), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes
is more direct/efficient.
stringByAddingPercentEscapesUsingEncoding:
, but stringByAddingPercentEncodingWithAllowedCharacters:
works fine with every character. Example: URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
–
Erne stringByAddingPercentEncodingWithAllowedCharacters
, but you cannot use URLQueryAllowedCharacterSet
, as that includes +
and &
(those are permitted character within the broader query, but if those characters appear within a value within a query, they must escaped, which that character set won't do). So, you can either use URLQueryAllowedCharacterSet
to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch. Or use CFURLCreateStringByAddingPercentEscapes
. –
Tetraploid CFURLCreateStringByAddingPercentEscapes
is now deprecated, you really should build the appropriate character set yourself. See https://mcmap.net/q/246437/-how-to-submit-a-password-with-special-characters-from-app-to-a-web-server-by-nsurlconnection. –
Tetraploid NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
Any one looking for a swift solution
let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)
© 2022 - 2024 — McMap. All rights reserved.