0

我有个问题:

我需要使用 json 向 php 发帖,但它只响应数据类型 x-www-form-urlencoded,我使用了谷歌浏览器的邮递员而不是表单数据完成,我用这种方式但告诉我参数不正确,我需要帮助:

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];
4

2 回答 2

1

For starters:

  1. Your string has nothing to do with JSON. It's just a plain string
  2. Your username & password must be URL encoded
  3. [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]] is wrong. You would have to use [NSData dataWithBytes:[jsonRequest UTF8String] length:[[jsonRequest UTF8String] length]]
于 2013-08-28T12:45:24.973 回答
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方法
于 2013-08-28T13:03:44.623 回答