如何在iOS中使用POST?

发布时间请求

NSString *str = [NSString stringWithFormat:@"{\"userId\":\"733895\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}"]; NSData *responseData = [str dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]]; [request setHTTPMethod:@"POST"]; NSError *error1 = nil; NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error1]; NSData *jsonData1 = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error1]; if (jsonData1) { 

处理数据

 [request setHTTPBody:jsonData1]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Assigned"]; (void)[[NSURLConnection alloc] initWithRequest:request delegate:self]; } 

我在这里没有得到答复。

 NSLog(@"%@",responseData); 

尝试这个

 NSString *strUserName = @"733895"; NSString *StartDate = @"24-04-2016"; NSString *EndDate = @"25-04-2016"; NSString * str = [NSString stringWithFormat:@"userId=%@&startDate=%@&endDate=%@", strUserName, StartDate,EndDate]; NSURL *url=[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]]; [request setTimeoutInterval:30.0]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (data) { // Success NSError *err; NSDictionary *APIResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err]; NSLog(@"%@",APIResponse); } else { // No Data --> Failed } }]; 

你应该做一些像

  NSString *str = [NSString stringWithFormat:@"{\"userId\":\"733895\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}"]; NSData *postData = [str dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //handle response here // you got response as data convert it in json object if response format is array or dictnary //convert it to string if format is string //you can convert it in json object like id jsonOb = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; //or you can get string like NSString *resultStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; }]; [dataTask resume]; 

问题是(a)你如何实现NSURLConnectionDataDelegate方法; 或(b)您的服务器如何处理请求。

在第一个问题上,因为无论如何NSURLConnection已被弃用,我们可以使用NSURLSession ,简化您的代码,并消除NSURLConnection数据源和委托代码的潜在问题来源:

 NSError *encodeError; NSDictionary *parameters = @{@"userId":@"733895",@"startDate":@"24-04-2016",@"endDate":@"25-04-2016"}; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://15.0.3.1/FFDCollector/timeSheet"]]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&encodeError]]; NSAssert(request.HTTPBody, @"Encoding failed: %@", error); NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { NSLog(@"Network error: %@", error); } if (data == nil) { return; } NSError *parseError; NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; if (!responseObject) { NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"could not parse; responseString = %@", responseString); return; } NSLog(@"Everything ok; responseObject = %@", responseObject); }]; [task resume]; 

请注意,我也整理了JSON请求的构build。 更重要的是,我也在做error handling,所以如果JSON响应不能被parsing,我们可以看到为什么。

就无法处理响应的原因而言,Web服务代码可能存在问题。 例如,Web可能会生成对application/x-www-form-urlencoded请求的JSON响应。 这可能是很多事情。 但是如果不做这个日志logging,你永远不会知道为什么会失败。


请注意,在iOS 9中,您需要告诉您的项目您愿意接受不安全的连接到您的Web服务。 因此,右键单击info.plist ,“打开为” – “源代码”,然后添加以下内容:

 <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>15.0.3.1</key> <dict> <!--Include to allow subdomains--> <key>NSIncludesSubdomains</key> <true/> <!--Include to allow HTTP requests--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <!--Include to specify minimum TLS version--> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.1</string> </dict> </dict> </dict>