2014-10-07 31 views
2

我想发布一些数据,加入烧瓶中的服务器,其代码如下:如何使Swift HTTP POST成为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.json.get('description', ""), 
    } 

    return jsonify({'task' : task}), 201 

当我运行它,它工作正常,我可以成功地使用curl使POST请求,与预期的行为在上面的后端和命令行中的预期返回值。然而,我想使用Swift发布到这个服务器上,并且遇到了麻烦。我已经按照教程详细说明了这种行为here。特别是,我将代码放在我的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 
} 

然而,当我启动这个程序,我有以下的在我的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 

我登录我一直在处理这个问题,并且对输入进行修改,似乎后端是好的,但我想知道这个前端有什么问题,不幸的是,Swift文档目前在这一点上相当有争议,似乎是这是目前唯一可用于RESTful API调用的解决方案。

回答

1

您的烧瓶路线是'/tasks',而您正尝试发送到http://localhost:5000/task。这是一个错字,还是你是复数失败的受害者?

+0

这一直是一个非常尴尬的学习经验 – mike 2014-10-07 20:12:39

+0

适合每个人。有时你只需要另一双眼睛。 – 2014-10-07 20:26:53

+0

在响应中使用更好的消息进行更好的错误处理可能是一个更好的主意。 – user805981 2015-03-18 01:22:37

相关问题