【问题标题】:NSURLRequest: How to change httpMethod "GET" to "POST"NSURLRequest:如何将 httpMethod“GET”更改为“POST”
【发布时间】:2011-10-13 06:54:01
【问题描述】:

GET 方法,效果很好。

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


我没有 POST 方法的概念。请帮帮我。

如何将 GET 方法更改为 POST 方法?


网址:http://testurl.com/test.html

[urlRequest setHTTPMethod:@"POST"];

【问题讨论】:

标签: iphone ios post nsurlrequest


【解决方案1】:

试试这个

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:。
  • { [请求 setHTTPMethod:@"POST"]; } 给出一个错误:- 不能为 HTTPMethod 赋值,它是一个只能获取的属性。你能帮帮我吗?
  • 也许你使用的是 MSURLRequest 而不是 NSMutableURLRequest
【解决方案2】:
// 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];

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    相关资源
    最近更新 更多