-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPRPFormEncodedPOSTRequest.m
53 lines (47 loc) · 1.86 KB
/
PRPFormEncodedPOSTRequest.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/***
* Excerpted from "iOS Recipes",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/cdirec for more book information.
***/
//
// NSMutableURLRequest+PRPAdditions.m
// BasicHTTPPost
//
// Created by Matt Drance on 9/20/10.
// Copyright 2010 Bookhouse Software, LLC. All rights reserved.
//
#import "PRPFormEncodedPOSTRequest.h"
#import "NSString+PRPURLAdditions.h"
@implementation PRPFormEncodedPOSTRequest
+ (id)requestWithURL:(NSURL *)url formParameters:(NSDictionary *)params {
return [[[self alloc] initWithURL:url formParameters:params] autorelease];
}
- (id)initWithURL:(NSURL *)url formParameters:(NSDictionary *)params {
if ((self = [super initWithURL:url])) {
[self setHTTPMethod:@"POST"];
[self setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
[self setFormParameters:params];
}
return self;
}
- (void)setFormParameters:(NSDictionary *)params {
NSStringEncoding enc = NSUTF8StringEncoding;
NSMutableString *postBody = [NSMutableString string];
for (NSString *paramKey in params) {
if ([paramKey length] > 0) {
NSString *value = [params objectForKey:paramKey];
NSString *encodedValue =
[value prp_URLEncodedFormStringUsingEncoding:enc];
NSUInteger length = [postBody length];
NSString *paramFormat = (length == 0 ? @"%@=%@" : @"&%@=%@");
[postBody appendFormat:paramFormat, paramKey, encodedValue];
}
}
NSLog(@"postBody is now %@", postBody);
[self setHTTPBody:[postBody dataUsingEncoding:enc]];
}
@end