2014-09-20 154 views
1

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

我试过如下

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."} 
+0

“Some URL “不是一个有效的URL!你有没有尝试向其他程序发布一些内容以确保其正常工作? – folkol 2014-09-20 09:13:26

+0

嘿@Madhu检查我的答案。,,,, – 2014-09-20 09:21:42

回答

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); 
+0

尝试第一个,但得到相同的错误 在第二个例子中,我们必须发送body.But我的要求是没有身体。 – Madhu 2014-09-20 09:28:15

+0

你可以试试我的第一个例子>>> – 2014-09-22 04:31:46