我遇到了NSMutableURLRequest的问题,我想翻译这个
curl -b $cookie -F "data=foo" -F "user=bar" http://some/stuff.cgi -H 'X-Requested-With: XMLHttpRequest
我的代码是
NSString *params = [NSString stringWithFormat:@"data=%@&user=bar", aUrl];
NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:[NSString stringWithFormat:@"http://%@:%d/stuff.cgi", _host, _port]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding ]];
[request setValue:[NSString stringWithFormat:@"http://%@/stuff.php", _host] forHTTPHeaderField:@"Referer"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
NSArray *availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@", _host]]];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
[request setAllHTTPHeaderFields:headers];
NSLog(@"headers: %@", [request allHTTPHeaderFields]);
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
...
但它不起作用,我搜索没有结果,我不知道问题出在哪里。
感谢。
答案 0 :(得分:0)
解决,只是指定长度
[request setValue:[[NSString alloc] initWithFormat:@"%d", [params length]] forHTTPHeaderField:@"Content-Length"];