我正在尝试查询以获取用Swift编写的iOS应用程序的指定汽车的燃料类型和消耗(用户输入品牌和型号)。
该应用针对西班牙,我找到了一个允许用户输入品牌和型号的网站,并返回该车的详细信息(http://coches.idae.es/portal/BaseDatos/MarcaModelo.aspx)。我见过使用WireShark工具,查询基于POST而不是GET。但我不太确定如何在我正在开发的应用程序中提出请求,或者如何处理从发件人发回给我的信息。
有没有办法向指定的网站提出这些请求?如果是这样,我真的很感激这个主题的一些帮助,我是iOS开发的新手,我期待尽可能多的学习。
谢谢:)
答案 0 :(得分:0)
许多人更喜欢使用AFNetworking来发出HTTP请求。但是你不需要这样做。你说它是一个POST请求。即使没有使用NSMutableURLRequest
的AFNetworking,设置也很容易。我假设您有一个API链接,而不仅仅是aspx页面。我的西班牙语非常弱,所以我无法为您查找API参考,但这里是如何发出请求并从服务器接收数据的。您必须输入正确的值并解析响应:
let request = NSMutableURLRequest(URL: NSURL(string: "/* Paste URL here */")!)
request.HTTPMethod = "POST"
// Do this as many times are required for filling in the headers.
request.addValue("/* The value for the HTTP header */", forHTTPHeaderField: "/*The header field like Accept-Type, etc..*/")
// If you need an HTTP body too then make the JSONObj as a dictionary or array or whatever and then
let data = NSJSONSerialization.dataWithJSONObject(JSONObj, options: [])
request.HTTPBody = data // This needs to be NSData.
// Now make the request.
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, { (data, response, error) -> Void in
if error == nil
{
assert(data != nil)
let JSON = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject]
// If you are using swift 2 this needs to be in a do try catch statement.
// TODO: Use JSON for whatever.
}
else
{
print(error!.localizedDescription)
}
}
task?.resume()
如果您有任何其他问题,或者API没有使用JSON或完全不同,请告诉我。