GET方法,它工作正常。NSURLRequest:如何將httpMethod「GET」更改爲「POST」
網址:http://myurl.com/test.html?query=id=123&name=kkk
我沒有POST方法的概念。請幫幫我。
我該如何改變GET方法到POST方法?
網址:http://testurl.com/test.html
[urlRequest setHTTPMethod:@"POST"];
GET方法,它工作正常。NSURLRequest:如何將httpMethod「GET」更改爲「POST」
網址:http://myurl.com/test.html?query=id=123&name=kkk
我沒有POST方法的概念。請幫幫我。
我該如何改變GET方法到POST方法?
網址:http://testurl.com/test.html
[urlRequest setHTTPMethod:@"POST"];
試試這個
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);
}
您可能想要刪除那個'[request setHTTPBody:'坐在那裏。 –
{[request setHTTPMethod:@「POST」]; }給出一個錯誤: - 不能將值賦給HTTPMethod,它是一個get only屬性。你可以幫我嗎? – Aashish
// 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];
我想他是問如何發送參數... – lluismontero
已更新我的回答 – Nekto
看看http://stackoverflow.com/questions/787582/nsurlrequest-encode- url-for-nsurlrequest-post-body-iphone-objective-c – lluismontero