2014-10-17 52 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