post method not work when i post the data using nsmutableurlrequest and nsurlconnection?

198 views Asked by At

I want to send my deviceid device type and phone number to server when I click on a button. I wrote my code here but it's not functioning properly. I dont know whats the problem is.

- (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

There are 2 answers

1
try catch finally On

Try and use this:

- (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];


}

Thanks.

0
Anuj On

The possible mistakes that i have seen in your code are

1) in your post string i.e.

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

You have & just Before DeviceId which i don't think should be there.

2) in request object,where you setting the content type for http header i.e.

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

you are writing Current-Type which is actually Content-Type