如何在ios中发送没有正文的json POST请求?

时间:2014-09-20 09:08:39

标签: ios json

我想在ios中发送没有正文的帖子请求

我试过如下

 NSString *url = [NSString stringWithFormat:@"Some URL"];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPMethod: @"POST"];

[NSURLConnection connectionWithRequest:request delegate:self];

我收到以下错误

Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo=0x15d62ed0 
NSLocalizedDescription=Could not connect to the server., 
NSUnderlyingError=0x15e522a0 "Could not connect to the server."}

1 个答案:

答案 0 :(得分:0)

NSString *appurl=[NSString stringWithFormat:@"Some URL"];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString  *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(@"%@",returnString);

OR

NSString *post =[NSString stringWithFormat:@"email=%@&pw=%@",[_txt_email.text lowercaseString],_txt_password.text];
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:@"%@login_new.php",app.Main_url]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);