如何在iOS中使用POST? [英] How to use POST in iOS?
问题描述
发布时间表请求
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];
}
我在这里没有得到答复.
I'm not getting the response here.
NSLog(@"%@",responseData);
推荐答案
问题是(a)如何实现NSURLConnectionDataDelegate
方法;或(b)您的服务器如何处理请求.
The problem is either (a) how you implemented the NSURLConnectionDataDelegate
methods; or (b) how your server processed the request.
在第一个问题上,由于无论如何都弃用了NSURLConnection
,我们可以使用NSURLSession
,简化您的代码,并消除NSURLConnection
数据源和委托代码的潜在问题根源:
On that first issue, because NSURLConnection
is deprecated anyway, we can use NSURLSession
, simplify your code, and eliminate the potential source of problem of the NSURLConnection
data source and delegate code:
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请求的结构.更重要的是,我也在进行错误处理,因此,如果无法解析JSON响应,我们可以了解原因.
Note, I tidied up the building of the JSON request, too. More importantly, I'm also doing error handling, so if the JSON response can't be parsed, we can see why.
就无法处理响应的原因而言,Web服务代码中可能存在问题.例如,也许网络会生成对application/x-www-form-urlencoded
请求的JSON响应.可能有很多事情.但是如果不执行此日志记录,您将永远不知道为什么会失败.
In terms of reasons why the response cannot be processed, there could be an issue in the web service code. For example, perhaps the web generates JSON response to application/x-www-form-urlencoded
requests. It could be many things. But without doing this logging, you will never know why it failed.
请注意,在iOS 9中,您需要告诉项目您愿意接受与Web服务的不安全连接.因此,右键单击info.plist
,打开为"-源代码",然后将以下内容添加到其中:
Note, in iOS 9, you need to tell your project that you're willing to accept insecure connections to your web service. So right-click on the info.plist
, "Open As" - "Source code" and then add the following to it:
<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>
这篇关于如何在iOS中使用POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!