1

我正在尝试实现一个 Objective C 程序来与 activeCollab 3 beta 交互并且遇到了一些问题。我可以在浏览器中输入 NSLog 输出的 url,它可以很好地为所有项目拉取 xml,当我尝试通过这个程序访问它时它不想为我工作,它给了我一个 HTTP 403错误。我是 Objective C 的新手,并且将其作为学习经验,因此某些代码可能是多余的。提前感谢您的帮助。导入用尖括号括起来,但会导致它在 StackOverflow 上被隐藏,所以我把它放在引号中

#import "基础/Foundation.h"

int main (int argc, const char * argv[]) {

    NSString *token = @"my-token";
    NSString *path_info = @"projects";
    NSString *url = @"http://my-site/api.php?";

    NSString *post = [[NSString alloc] initWithFormat:@"path_info=%@&auth_api_token=%@",path_info, token];
    NSLog(@"发帖:%@", 发帖);

    NSString *newRequest;
    newRequest = [url stringByAppendingString:post];

    NSLog(@"路径:%@", newRequest);

    NSData *postData = [newRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    [请求 setURL:[NSURL URLWithString:newRequest]];
    [请求 setHTTPMethod:@"POST"];
    [请求 setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [请求 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [请求 setHTTPBody:postData];

    NSURLResponse *响应;
    NSError *错误;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returnedResponse:&response error:&err];

    NSString *returnData = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"%@", returnData);

    //printf("打印行");
    返回0;
}
4

1 回答 1

0

您的请求标头是限制性和不必要的,对于 AC API,您需要 GET 请求而不是 POST

int main (int argc, const char * argv[]) 
{

    NSString *requestString = [[NSString alloc] initWithFormat:@"path_info=%@&auth_api_token=%@", path_info, token];
    NSLog(@"Post: %@", requestString);

    NSString *newRequest;
    newRequest = [url stringByAppendingString: requestString];

    NSLog(@"Path: %@", newRequest);

    NSData *postData = [newRequest dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

    NSLog(@"Data: %@", postData);

    [request setURL: [NSURL URLWithString:newRequest]];
    [request setHTTPMethod: @"GET"];

    NSURLResponse *response;

    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &err];
    NSString *returnData = [[[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding] autorelease];
    NSLog(@"Return: %@", returnData);

    //printf("Print line");
    return 0;
}
于 2012-07-04T07:01:50.727 回答