2014-10-17 83 views
0

它是我第一次在堆栈溢出中,所以很好:P。这是我的方法,应该发送一些信息到我的网络服务器。用Objective-C发送POST并使用python使用python获取POST

-(IBAction)updateEvent:(id)sender{ 

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; 

    [[dict objectForKey:@"name"] addObject:_getNameLabel.text]; 

    static NSString *url = @"http://localhost:5000/hello"; 
    NSError *error; 
    NSData *event = [NSJSONSerialization dataWithJSONObject:dict 
                 options:NSJSONWritingPrettyPrinted 
                 error:&error]; 

    if (! event) { 
     NSLog(@"Got an error: %@", error); 
    } else { 
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setHTTPMethod:@"POST"]; 
     [request setHTTPBody:event]; 
     [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[event length]] forHTTPHeaderField:@"Content-Length"]; 
     [request setURL:[NSURL URLWithString:url]]; 
    } 


    // [gameInfoObject postEventInfo:event]; 

} 

这里是“应该”处理邮件的代码。我想要做的就是获取这些信息并将其写入现有文件。

import pickle 
from flask import Flask 
import json 

@app.route('/hello/' , methods=['POST']) 
def test(): 

    with open("text.txt", "w") as text_file: #to check that it even gets here but it does not write anything at all to the file 
     text_file.write("It came here!!") 

    data = request.data 
    dataDict = json.loads(data) 

    with open('gameFile.txt', 'wb') as handle: 
     pickle.dump(dataDict, handle) 


if __name__ == "__main__": 
    app.run() 

因此,当我运行它,我得到没有错误,但我也没有得到任何结果。该文件仍然是空的,我在这里错过了什么?我感谢我能得到的所有帮助!

+0

在'def test'方法结束时尝试'return json.dumps({'msg':'success'})''。 – 2014-10-17 10:08:25

+0

我在哪里可以看到该消息? @SyedHabibM – 2014-10-17 10:09:44

+0

在你的'objective-c'代码响应中? – 2014-10-17 10:12:23

回答

0

您的网址不符。

您已将Flask中的路线定义为/hello/

@app.route('/hello/' , methods=['POST']) 

但是,当您从Objective-C发出请求时,请将其发送到/hello

static NSString *url = @"http://localhost:5000/hello"; 

当瓶接收它发送带有301状态码告诉客户端的资源已经被移动到/hello/一个响应该请求。客户端不遵循重定向。

要么更新您的路线或更新您的请求,你应该全部设置。

编辑:

您还没有发送请求。您发布的代码准备了POST请求,但您需要打开一个连接。我并不十分熟悉Objective-C,但它应该符合以下几点。

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                  delegate:self]; 

[connection start]; 
+0

但在浏览器中需要写入“http:// localhost:5000/hello“不只是你好吗? @dirn – 2014-10-17 12:56:21

+0

如果您在浏览器中访问'localhost:5000/hello',它将重定向到'localhost:5000/hello /'。 – dirn 2014-10-17 13:18:50

+0

阿哈现在我明白了嘿嘿。我只是将字符串url更改为@“http:// localhost:5000/hello /”,但它仍然无效:/ :(@dirn – 2014-10-17 14:19:41