我一直试图让这个代码工作发送一个种子的数据到µtorrent Web API,不幸的是,据我所知,没有人曾经试图在Objective-C之前为µtorrent做一个。torrent文件处理程序,这并不奇怪。
我有这个代码在这里的时刻,但我总是得到错误信息:"错误:种子文件的内容没有在形式参数提供"。
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?token=%@&action=add-file", [self getBaseURL], token]]];
NSString * boundary = @"!@!@!@!@!@!@!@!@!";
NSMutableData * body = [NSMutableData alloc];
NSData * torrentFileContents = [[NSFileManager defaultManager] contentsAtPath:fileName];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"enctype"];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@rnrn", @"application/x-bittorrent"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="torrent_file"; filename="%@"rn", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Length: %ldrn", [torrentFileContents length]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:torrentFileContents]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
为什么要将内容类型和长度放在请求正文中?您是否尝试使用setValue来添加必要的HTTP头,如Content-Type?
例如:[request addValue:@"text/xml;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
我找到了一个我想做的例子,用JS写的,我可以通过调整代码使其工作,看起来像这样。
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?token=%@&action=add-file", [self getBaseURL], token]]];
NSString * boundary = [NSString stringWithFormat:@"AJAX-----------------------%f", [[[NSDate alloc] init] timeIntervalSince1970]];
NSMutableData * body = [NSMutableData alloc];
NSData * torrentFileContents = [[NSFileManager defaultManager] contentsAtPath:fileName];
[request setHTTPMethod:@"POST"];
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"--%@rn", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="torrent_file"; filename="%@"rn", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@rnrn", @"application/x-bittorrent"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:torrentFileContents]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
return request;