【发布时间】:2016-08-09 05:45:04
【问题描述】:
在我的应用程序中,我需要将数据发布到服务器并需要接收响应。但是我在发布数据后得到空值。下面是我的完整代码。提前致谢。
{
NSString *post =[[NSString alloc] initWithFormat:@"%@%@%@%@%@",[self.username_reg text],[self.emailid_reg text],[self.phone_reg text],[self.password_reg text],[self.confirmpassword_reg text]];
NSLog(@"PostData: %@",post);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url=[NSURL URLWithString:@"https://servlet/URL"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:_username_reg.text forKey:@"UserName"];
[postDict setValue:_emailid_reg.text forKey:@"Email"];
[postDict setValue:_phone_reg.text forKey:@"Phone"];
[postDict setValue:_password_reg.text forKey:@"Pass"];
[postDict setValue:_confirmpassword_reg.text forKey:@"ConPass"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSLog(@"bcbc:%@",requestBodyData);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"new:%@",newStr);
NSError *error;
NSDictionary *json_Dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@",json_Dict);
}];
}
请求给出的格式是:
{"UserName":"sony","Email":"ronyv@example.in","Phone":"7358700457","Pass":"sony88","ConPass":"sony88"}
需要得到的响应:
{"responseHeader":{"responseCode":0,"responseMessage":"Success"}}
【问题讨论】:
-
使用AFNetworking怎么样?这可能不是您问题的答案。但是它很容易用于网络用途,最好的!
-
你能解释一下如何使用AFNetworking
-
AFNetworking :查看示例。
-
试试这个answer它可能会有所帮助。