在Google App Engine Python API中获取原始POST数据

3 投票
2 回答
3345 浏览
提问于 2025-04-15 19:12

我正在尝试通过自定义请求将原始数据以POST方式发送到Google App Engine,使用的是self.request.get('content'),但没有成功。它返回的是空值。我确定数据是从客户端发送的,因为我用另一段简单的服务器代码进行了检查。

你知道我哪里做错了吗?我在客户端使用以下代码来生成POST请求(objective-c/cocoa-touch)

NSMutableArray *array = [[NSMutableArray alloc] init];
    NSMutableDictionary *diction = [[NSMutableDictionary alloc] init];
    NSString *tempcurrentQuestion = [[NSString alloc] initWithFormat:@"%d", (questionNo+1)];
    NSString *tempansweredOption = [[NSString alloc] initWithFormat:@"%d", (answeredOption)];       

    [diction setValue:tempcurrentQuestion forKey:@"questionNo"];
    [diction setValue:tempansweredOption forKey:@"answeredOption"];
    [diction setValue:country forKey:@"country"];

    [array addObject:diction];
    NSString *post1 = [[CJSONSerializer serializer] serializeObject:array];


    NSString *post = [NSString stringWithFormat:@"json=%@", post1];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
    NSLog(@"Length: %d", [postData length]);

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
    [request setURL:[NSURL URLWithString:@"http://localhost:8080/userResult/"]];  
    [request setHTTPMethod:@"POST"];  
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];  
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];  
    [request setHTTPBody:postData];
    questionsFlag = FALSE;
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

服务器端的代码是:

class userResult(webapp.RequestHandler):
def __init__(self):
    self.qNo = 1
def post(self):
    return self.request.get('json')

2 个回答

7

self.request.get('content') 这个代码会让你获取到发送过来的名为 'content' 的数据。如果你想要获取原始的帖子数据,可以使用 self.request.body

4

试着用一种不同于 application/x-www-form-urlencoded 的内容类型来提交POST数据,这种类型是浏览器提交表单时的默认设置。如果你使用其他内容类型,原始的POST数据会在 self.request.body 中,就像Wooble建议的那样。

如果这个数据实际上是来自一个HTML表单,你可以在 <form> 标签中添加 enctype 属性,来改变浏览器使用的编码方式。你可以试试像 enctype="application/octet-stream" 这样的设置。

撰写回答