2010-11-24 57 views
48

有沒有什麼辦法可以將HTTP頭添加到NSURLRequest對象?我曾經將它們添加在NSMutableURLRequest使用:添加HTTP頭到NSURLRequest

[request addValue:@"PC" forHTTPHeaderField:@"machineName"] 

回答

79

我不認爲你可以修改NSURLRequest的HTTP頭。我想你試圖修改一個你沒有初始化的NSURLRequest對象?

您可以創建您的要求進行mutableCopy,然後設置下面的方法將頭字段:

-(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field. 

那之後,你可以copy易變的請求返回到您的NSURLRequest變量。

編輯:下面

/* Create request variable containing our immutable request 
* This could also be a paramter of your method */ 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]]; 

// Create a mutable copy of the immutable request and add more headers 
NSMutableURLRequest *mutableRequest = [request mutableCopy]; 
[mutableRequest addValue:@"Hless" forHTTPHeaderField:@"X-user-nick"]; 

// Now set our request variable with an (immutable) copy of the altered request 
request = [mutableRequest copy]; 

// Log the output to make sure our new headers are there  
NSLog(@"%@", request.allHTTPHeaderFields); 
+1

感謝您的答覆中,事情是你不能添加HTTP頭到NSURLRequest你只能得到它們,說實話我想使用NSURLRequest,因爲我想使用委託「didRece」接收一個分塊文件iveData「,但現在我正在使用線程,而不是NSMutableURLRequest。 – 2010-11-24 10:12:54

+0

我知道我已經發布了一段時間了,但由於有點流行的需求,我更新了正確答案並添加了一個例子。 – Hless 2013-09-03 10:47:47

5
NSString *urlString = @"http://10.28.79.63:3000/testing"; 

NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] init] ; 
[imageRequest setURL:[NSURL URLWithString:urlString]]; 
[imageRequest setHTTPMethod:@"POST"]; 

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 

[imageRequest setValue:contentType forHTTPHeaderField: @"content-Type"]; 
NSMutableData *body = [NSMutableData dataWithCapacity:[imageData length] + 512]; 
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]]; 

//Here u adds the Headers which will be posted in body 

[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; content-type: application/octet-stream; name=\"userfile\"; filename=\"inLove.mp4\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 


[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

[imageRequest setHTTPBody:body]; 
NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:imageRequest 
               delegate:self]; 
7

,將實施例已經回答了(和感謝那些答案),但這裏有一個更簡單的例子:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; 
[request setValue:@"es" forHTTPHeaderField:@"Accept-Language"];