我遇到了问题:
我需要使用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];
答案 0 :(得分:1)
首先:
[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
更改为其他内容。NSURLConnectionDelegate
方法