数据类型application / x-www-form-urlencoded from json error

时间:2013-08-28 12:38:47

标签: ios objective-c json

我遇到了问题:

我需要使用json发布到php的帖子,但它只响应数据类型x-www-form-urlencoded,我使用google chrome的邮递员而不是form-data完成,我用这种方式但告诉我参数不正确,我需要帮助:

NSString *jsonRequest = [NSString stringWithFormat:@"j_username=%@&j_password=%@",nombre,pass];
NSURL *url = [NSURL URLWithString:urlhttp];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:request delegate:self];

2 个答案:

答案 0 :(得分:1)

首先:

  1. 您的字符串与JSON无关。它只是一个简单的字符串
  2. 您的用户名&密码必须是URL编码的
  3. [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]]错了。您必须使用[NSData dataWithBytes:[jsonRequest UTF8String] length:[[jsonRequest UTF8String] length]]

答案 1 :(得分:0)

您的示例中的JSON在哪里?在示例中,您没有任何外观。 你在设置请求时遇到了一些错误,请查看Sulthan的答案。

我的建议是使用一个库来处理诸如编码和标题之类的小型正式细节。

使用AFNetworking,您可以编写类似的内容。

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://whatever.com/"]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding]

NSDictionary * params = @{
                           @"j_username": nombre,
                           @"j_password": pass
                         };
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"relative/path/to/resource"
                                                  parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[httpClient enqueueHTTPRequestOperation:operation];

(基于http://samwize.com/2012/10/25/simple-get-post-afnetworking/的例子)

虽然就LOC而言可能看起来不那么好,但请考虑:

  • httpClient仅初始化一次,您可以将其重复用于后续请求,集中配置
  • 参数会以所需的格式自动编码,如果您以后必须更改编码,则只需将AFFormURLParameterEncoding更改为其他内容。
  • 你得到一个不错的基于块的API,而不是依赖繁琐的NSURLConnectionDelegate方法