当我使用nsmutableurlrequest和nsurlconnection发布数据时,post方法不起作用?

时间:2013-12-03 12:45:28

标签: iphone post ios7 xcode5 nsmutableurlrequest

我想在点击按钮时将我的deviceid设备类型和电话号码发送到服务器。 我在这里写了我的代码,但是它运行不正常。我不知道问题是什么。

- (IBAction)sendPostData:(id)sender  {

 NSString *post=[NSString stringWithFormat:@"&DeviceId=mac123&DeviceType=ios&Phone=%@",phoneNumberTxt.text];

 NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
 NSString *postLength =[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
 NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
 [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.27:8080/MeetingPoint/api/Register"]]];
 [request setHTTPMethod:@"POST"];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
 [request setHTTPBody:postData];

 NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];

 [connection start];

 if (connection) {
    NSMutableData *mydata=[[NSMutableData alloc]init]; 
    mydata=[NSMutableData data];
    NSLog(@"data is :%@",mydata);
  }

}

2 个答案:

答案 0 :(得分:0)

尝试并使用它:

- (IBAction)sendPostData:(id)sender  {

 NSString *post=[NSString stringWithFormat:@"&DeviceId=mac123&DeviceType=ios&Phone=%@",phoneNumberTxt.text];

 NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
 NSString *postLength =[NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
 NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
 [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.27:8080/MeetingPoint/api/Register"]]];
 [request setHTTPMethod:@"POST"];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
 [request setHTTPBody:postData];

 NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];


    NSMutableData *mydata=[[NSMutableData alloc]init]; 
    mydata=[NSMutableData data];
    NSLog(@"data is :%@",mydata);


 [connection start];


}

感谢。

答案 1 :(得分:0)

我在代码中看到的错误可能是

1)在你的帖子中,即

 NSString *post=[NSString stringWithFormat:@"&DeviceId=mac123&DeviceType=ios&Phone=%@",phoneNumberTxt.text];

你有&就在DeviceId之前,我认为不应该在那里。

2)在请求对象中,您设置http标题的内容类型,即

 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; 

您正在编写Current-Type,实际上是Content-Type