This repository has been archived by the owner on Oct 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Wrapper.m
290 lines (254 loc) · 9.86 KB
/
Wrapper.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//
// Wrapper.m
// WrapperTest
//
// Created by Adrian on 10/18/08.
// Copyright 2008 Adrian Kosmaczewski. All rights reserved.
//
#import "Wrapper.h"
@interface Wrapper (Private)
- (void)startConnection:(NSURLRequest *)request;
@end
@implementation Wrapper
@synthesize receivedData;
@synthesize asynchronous;
@synthesize mimeType;
@synthesize username;
@synthesize password;
@synthesize delegate;
#pragma mark -
#pragma mark Constructor and destructor
- (id)init
{
if(self = [super init])
{
receivedData = [[NSMutableData alloc] init];
conn = nil;
asynchronous = YES;
mimeType = @"text/html";
delegate = nil;
username = @"";
password = @"";
}
return self;
}
- (void)dealloc
{
[receivedData release];
receivedData = nil;
self.mimeType = nil;
self.username = nil;
self.password = nil;
[super dealloc];
}
#pragma mark -
#pragma mark Public methods
- (void)sendRequestTo:(NSURL *)url usingVerb:(NSString *)verb withParameters:(NSDictionary *)parameters
{
NSData *body = nil;
NSMutableString *params = nil;
NSString *contentType = @"text/html; charset=utf-8";
NSURL *finalURL = url;
if (parameters != nil)
{
params = [[NSMutableString alloc] init];
for (id key in parameters)
{
NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
CFStringRef value = (CFStringRef)[[parameters objectForKey:key] copy];
// Escape even the "reserved" characters for URLs
// as defined in http://www.ietf.org/rfc/rfc2396.txt
CFStringRef encodedValue = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
value,
NULL,
(CFStringRef)@";/?:@&=+$,",
kCFStringEncodingUTF8);
[params appendFormat:@"%@=%@&", encodedKey, encodedValue];
CFRelease(value);
CFRelease(encodedValue);
}
[params deleteCharactersInRange:NSMakeRange([params length] - 1, 1)];
}
if ([verb isEqualToString:@"POST"] || [verb isEqualToString:@"PUT"])
{
contentType = @"application/x-www-form-urlencoded; charset=utf-8";
body = [params dataUsingEncoding:NSUTF8StringEncoding];
}
else
{
if (parameters != nil)
{
NSString *urlWithParams = [[url absoluteString] stringByAppendingFormat:@"?%@", params];
finalURL = [NSURL URLWithString:urlWithParams];
}
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:@"Content-Type"];
[headers setValue:mimeType forKey:@"Accept"];
[headers setValue:@"no-cache" forKey:@"Cache-Control"];
[headers setValue:@"no-cache" forKey:@"Pragma"];
[headers setValue:@"close" forKey:@"Connection"]; // Avoid HTTP 1.1 "keep alive" for the connection
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:verb];
[request setAllHTTPHeaderFields:headers];
if (parameters != nil)
{
[request setHTTPBody:body];
}
[params release];
[self startConnection:request];
}
- (void)uploadData:(NSData *)data toURL:(NSURL *)url
{
// File upload code adapted from http://www.cocoadev.com/index.pl?HTTPFileUpload
// and http://www.cocoadev.com/index.pl?HTTPFileUploadSample
NSString* stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"];
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:@"no-cache" forKey:@"Cache-Control"];
[headers setValue:@"no-cache" forKey:@"Pragma"];
[headers setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary] forKey:@"Content-Type"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
NSMutableData* postData = [NSMutableData dataWithCapacity:[data length] + 512];
[postData appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"test.bin\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
[self startConnection:request];
}
- (void)cancelConnection
{
[conn cancel];
[conn release];
conn = nil;
}
- (NSDictionary *)responseAsPropertyList
{
NSString *errorStr = nil;
NSPropertyListFormat format;
NSDictionary *propertyList = [NSPropertyListSerialization propertyListFromData:receivedData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&errorStr];
[errorStr release];
return propertyList;
}
- (NSString *)responseAsText
{
return [[[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding] autorelease];
}
#pragma mark -
#pragma mark Private methods
- (void)startConnection:(NSURLRequest *)request
{
if (asynchronous)
{
[self cancelConnection];
conn = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
if (!conn)
{
if ([delegate respondsToSelector:@selector(wrapper:didFailWithError:)])
{
NSMutableDictionary* info = [NSMutableDictionary dictionaryWithObject:[request URL] forKey:NSErrorFailingURLStringKey];
[info setObject:@"Could not open connection" forKey:NSLocalizedDescriptionKey];
NSError* error = [NSError errorWithDomain:@"Wrapper" code:1 userInfo:info];
[delegate wrapper:self didFailWithError:error];
}
}
}
else
{
NSURLResponse* response = [[NSURLResponse alloc] init];
NSError* error = [[NSError alloc] init];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[receivedData setData:data];
[response release];
response = nil;
[error release];
error = nil;
}
}
#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSInteger count = [challenge previousFailureCount];
if (count == 0)
{
NSURLCredential* credential = [[NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceNone] autorelease];
[[challenge sender] useCredential:credential
forAuthenticationChallenge:challenge];
}
else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
if ([delegate respondsToSelector:@selector(wrapperHasBadCredentials:)])
{
[delegate wrapperHasBadCredentials:self];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int statusCode = [httpResponse statusCode];
switch (statusCode)
{
case 200:
break;
case 201:
{
NSString* url = [[httpResponse allHeaderFields] objectForKey:@"Location"];
if ([delegate respondsToSelector:@selector(wrapper:didCreateResourceAtURL:)])
{
[delegate wrapper:self didCreateResourceAtURL:url];
}
break;
}
// Here you could add more status code handling... for example 404 (not found),
// 204 (after a PUT or a DELETE), 500 (server error), etc... with the
// corresponding delegate methods called as required.
default:
{
if ([delegate respondsToSelector:@selector(wrapper:didReceiveStatusCode:)])
{
[delegate wrapper:self didReceiveStatusCode:statusCode];
}
break;
}
}
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self cancelConnection];
if ([delegate respondsToSelector:@selector(wrapper:didFailWithError:)])
{
[delegate wrapper:self didFailWithError:error];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self cancelConnection];
if ([delegate respondsToSelector:@selector(wrapper:didRetrieveData:)])
{
[delegate wrapper:self didRetrieveData:receivedData];
}
}
@end