我想从我的应用程序发出以下请求:
AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
requestManager.responseSerializer.acceptableContentTypes = [requestManager.responseSerializer.acceptableContentTypes setByAddingObject:@"application/json"];
requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
[requestManager POST:urlString parameters:aParameters constructingBodyWithBlock:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"error: %@", error);
}];
其中aParameters是具有以下内容的NSDictionary:
NSDictionary *urlParams = @{@"username" : anUser.userName, @"password" : anUser.password};
当我使用" anUsername"的用户输入从我的应用程序发出请求时和" aPassword"我在servlet中获取了以下日志:
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="password"
aPassword
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="username"
anUsername
--Boundary+5738A89B2C391231--
multipart/form-data; boundary=Boundary+5738A89B2C391231
我的印象是使用AFJSONRequestSerializer会以适当的格式发送我的请求,但正如日志所示,它是多部分/表单数据。解析这种请求(我在服务器端用Java解析它)真的很难(对我来说),所以我的问题是:是否有可能在我的请求正文中发送一个json?像这样:
{
"userName" : "anUsername",
"password" : "aPassword"
}
任何帮助都将不胜感激。
答案 0 :(得分:5)
对于任何关注的人:您应该使用POST:parameters:constructingBodyWithBlock:success:failure:
,而不是使用POST:parameters:success:failure:
方法。前者执行多部分表单请求,而后者执行url表单编码。此外,要以JSON格式发送params,requestSerializer
实例的AFHTTPRequestOperationManager
属性应该是AFJSONRequestSerializer
的实例(默认设置为AFHTTPRequestSerializer
)
浏览AFHTTPRequestOperationManager
的实现文件非常有用,可以帮助我排除这个错误。
答案 1 :(得分:3)
您不需要在POST请求中发送纯JSON,只需发送参数字典。以下是适用于POST请求的示例代码。
+ (void)login:(BOUser *)user responseBlock:(APIRequestResponseBlock)responseBlock {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"parse-application-id-removed" forHTTPHeaderField:@"X-Parse-Application-Id"];
[manager.requestSerializer setValue:@"parse-rest-api-key-removed" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
NSString *URLString = [NSString stringWithFormat:@"%@login", BASE_URL_STRING];
NSDictionary *params = @{@"email": user.username,
@"password": user.password};
[manager POST:URLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
responseBlock(nil, FALSE, error);
}];
}
我希望它有所帮助。