我正在尝试向链接发出 HTTP 请求;响应采用 JSON 格式。
我无法正确获得响应。我是 Swift 的新手,我不知道问题出在哪里……
我要访问的 URL 是 http://url/test.r&pcTest=pTest
我已经这样做了,但是在 Objective C 中:
NSString *serviceURL = [NSString stringWithFormat:@"http://url/test.r&pcTest=pTest"];
NSURL *URL = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSData *data = [NSData dataWithContentsOfURL:URL];
if (!data) {
NSLog(@"null");
}
NSString *response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;
if (![response isEqualToString:@"UNAUTHORIZED"]) {
response = [response stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
data = [response dataUsingEncoding:NSASCIIStringEncoding];
NSLog(@"%@",response);
} else {
//return nil;
NSLog(@"dsfg");
}
我得到了正确答案。在 Swift 中,我的代码是:
let parameters = ["pcTest": "pTest"]
let urlPath :String = "http://url/test.r"
Alamofire.request(.POST, urlPath, parameters: parameters)
.response { request, response, data, error in
println(request)
println(response)
println(error)
println(data)
}
响应是
{ URL: http://url/test.r }
Optional( { URL: http://url/test.r} { status code: 200, headers { Connection = "Keep-Alive"; "Content-Type" = "text/javascript; charset=iso-8859-1"; Date = "Fri, 11 Sep 2015 22:34:12 GMT"; "Keep-Alive" = "timeout=5, max=400"; Server = "Apache/1.3.41 (Unix) mod_ssl/2.8.31 OpenSSL/0.9.8c"; "Transfer-Encoding" = Identity; } })
nil
Optional(<7b227474 41706172 7461646f 223a5b7b 22416e6f 223a2232 30313422 2c224376 655f4170 6172745f 4576616c 7561223a 22303122 2c224465 73637269 7063696f 6e223a22 43616c69 64616420 656e2065 6c204465 73656d70 65f16f20 446f6365 6e746522 7d2c7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3032222c 22446573 63726970 63696f6e 223a2244 65646963 616369f3 6e206120 6c617320 41637469 76696461 64657320 64652044 6f63656e 63696122 7d2c7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3033222c 22446573 63726970 63696f6e 223a2250 65726d61 6e656e63 69612065 6e206c61 73204163 74697669 64616465 73206465 20446f63 656e6369 61227d5d 2c227474 53656363 696f6e22 3a5b7b22 416e6f22 3a223230 3134222c 22437665 5f417061 72745f45 76616c75 61223a22 3031222c 22437665 5f536563 635f4576 616c7561 223a2230 31222c22
响应应该是:
{"Bank":[{"Year":"2014","Clv":"01","Desc":"1345"},{"Year":"2014","Clv ... etc, etc
最佳答案
如果要JSON解析,需要调用responseJSON
,而不是response
:
let parameters = ["pcTest": "pTest"]
Alamofire.request(.GET, "http://url/test.r", parameters: parameters)
.responseJSON { _, _, result in
print(result)
debugPrint(result)
}
关于ios - Swift 中的 Alamofire HTTP post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32533132/