2011-10-13 27 views
8

Phương thức GET, nó hoạt động tốt.NSURLYêu cầu: Cách thay đổi httpMethod "GET" thành "POST"

url: http://myurl.com/test.html?query=id=123&name=kkk


Tôi không có khái niệm về phương thức POST. Làm ơn giúp tôi.

Làm cách nào tôi có thể chagne GET method to POST method?


url: http://testurl.com/test.html

[urlRequest setHTTPMethod:@"POST"];

+0

Hãy xem http://stackoverflow.com/questions/787582/nsurlrequest-encode- url-for-nsurlrequest-post-body-iphone-objective-c – lluismontero

Trả lời

20

thử này

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",username.text,password.text]; 
NSLog(@"%@",post); 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@" server link here"]]]; 
[request setHTTPMethod:@"POST"]; 
NSString *json = @"{}"; 
NSMutableData *body = [[NSMutableData alloc] init]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; 
[request setHTTPBody:postData]; 
//get response 
NSHTTPURLResponse* urlResponse = nil; 
NSError *error = [[NSError alloc] init]; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"Response Code: %d", [urlResponse statusCode]); 

if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) 
{ 
    NSLog(@"Response: %@", result); 
} 
+1

Bạn có thể muốn xóa '[request setHTTPBody:' đang ngồi ở đó. –

+0

{[yêu cầu setHTTPMethod: @ "POST"]; } đưa ra một lỗi: - không thể gán giá trị cho HTTPMethod, một thuộc tính của nó chỉ nhận được. Bạn có thể giúp tôi được không? – Aashish

6
// create mutable request 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];  
// set GET or POST method 
[request setHTTPMethod:@"POST"]; 
// adding keys with values 
NSString *post = @"query=id=123&name=kkk"; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
[request addValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setHTTPBody:postData]; 
+0

Tôi nghĩ anh ấy đang hỏi cách gửi các đối số ... – lluismontero

+0

cập nhật câu trả lời của tôi – Nekto

Các vấn đề liên quan