我有一个EC2实例,我想从我的iPhone应用程序发送数据。我在服务器识别和保存数据到文本文件时遇到麻烦。
在Objective-C中我这样做了:
- (void) sendDataToServer:(NSString *)url : (NSString *) content{
// define your form fields here:
//NSString *content = @"field1=42&field2=Hello";
NSString *post = [NSString stringWithFormat:@"&Data=%@",content];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
NSData *contentData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:contentData];
NSString *postLength = [NSString stringWithFormat:@"%d",[contentData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// generates an autoreleased NSURLConnection
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn){
NSLog(@"connection");
mutableData = [[NSMutableData alloc] init];
}
//[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//[self doSomethingWithData:data];
NSLog(@"Success!");
if (error){
NSLog(@"ERROR: %@", error);
}
}];
}
在我的服务器上,我有flask工作正常。在.py文件中,我有如下内容:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def login():
if request.method == 'POST':
f = request.files['the_file']
f.save('#path-to-destination-folder')
if __name__ == '__main__':
app.run(host='0.0.0.0')
我知道我的服务器代码有问题。当我试图将数据发送到我的服务器时,我一直得到一个错误400。
如何将NSString保存为远程服务器上的文本文件?request.files
包含发送到服务器的文件。您只发送POST数据。可通过request.form
访问。
@app.route('/', methods=['POST'])
def login():
if request.method == 'POST':
data = request.form['Data']
with open('/path/to/file', 'w') as f:
f.write(data)
return 'some response that means ok'
在向文件系统写入内容之前,您可能想要做一些比这更健壮的事情,但这是您需要做的一般想法。
Data
可能不是正确的键。我不知道Objective-C,但看起来这是你用[NSString stringWithFormat:@"&Data=%@",content]
设置的