Python 如何使Swift HTTP POST命中Flask服务器?
我正在尝试将一些数据发布到Flask服务器,其代码如下:Python 如何使Swift HTTP POST命中Flask服务器?,python,ios,rest,swift,Python,Ios,Rest,Swift,我正在尝试将一些数据发布到Flask服务器,其代码如下: @app.route('/tasks', methods=['POST']) def create_task(): if not request.json or not 'title' in request.json: abort(400) task = { 'title': request.json['title'], 'description': request.jso
@app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'title': request.json['title'],
'description': request.json.get('description', ""),
}
return jsonify({'task' : task}), 201
当我运行这个程序时,它工作得很好,我可以使用curl成功地发出POST请求,在上面的后端有预期的行为,在命令行中有预期的返回值。我想用Swift发一篇帖子到这个服务器上,但是我遇到了麻烦。我遵循了详细介绍此行为的教程。特别是,我将代码放在我的AppDelegate.swift
中,以便在应用程序启动时立即执行。完整代码已发布在链接中,但我也将其发布在下面以供参考:
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["username":"jameson", "password":"password"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
return true
}
func应用程序(应用程序:UIApplication!,didfishlaunchingwithoptions启动选项:NSDictionary!)->Bool{
var request=NSMutableURLRequest(URL:NSURL(字符串):http://localhost:4567/login"))
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
var params=[“用户名”:“詹姆逊”,“密码”:“密码”]作为字典
变量错误:n错误?
request.HTTPBody=NSJSONSerialization.dataWithJSONObject(参数,选项:nil,错误:&err)
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
println(“响应:\(响应)”)
var strData=NSString(数据:数据,编码:NSUTF8StringEncoding)
println(“正文:\(strData)”)
变量错误:n错误?
var json=NSJSONSerialization.JSONObjectWithData(数据,选项:.MutableLeaves,错误:&err)作为?NSDictionary
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
如果(错误!=nil){
println(错误!.localizedDescription)
让jsonStr=NSString(数据:data,编码:NSUTF8StringEncoding)
println(“错误无法解析JSON:'\(jsonStr)'”)
}
否则{
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json{
//好的,parsedJSON在这里,让我们从中获得“成功”的价值
var success=parseJSON[“success”]as?Int
println(“成功:\(成功)”)
}
否则{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data,编码:NSUTF8StringEncoding)
println(“错误无法解析JSON:\(jsonStr)”)
}
}
})
task.resume()
返回真值
}
但是,当我启动此应用程序时,我的xcode中已登录以下内容
Response: <NSHTTPURLResponse: 0x7fc4dae218a0> { URL: http://localhost:5000/task } { status code: 404, headers {
"Content-Length" = 26;
"Content-Type" = "application/json";
Date = "Tue, 07 Oct 2014 19:22:57 GMT";
Server = "Werkzeug/0.9.6 Python/2.7.5";
} }
Body: {
"error": "Not found"
}
Succes: nil
响应:{URL:http://localhost:5000/task }{状态代码:404,标题{
“内容长度”=26;
“内容类型”=“应用程序/json”;
日期=“2014年10月7日星期二19:22:57 GMT”;
Server=“Werkzeug/0.9.6 Python/2.7.5”;
} }
正文:{
“错误”:“未找到”
}
成功:无
我一直在处理这个并修补输入,看起来后端很好,但我想知道前端出了什么问题,不幸的是,Swift文档在这一点上目前还没有定论,似乎是目前唯一一个RESTful API调用的解决方案。您的烧瓶路径是
'/tasks'
,您正试图发布到http://localhost:5000/task
。这是一个打字错误,还是你是多元化失败的受害者?每个人都会遇到这种情况。有时候你只需要另一双眼睛。在响应中使用更好的消息来更好地处理错误可能是一个更好的主意。