1

我正在尝试通过 http 发帖但没有成功这是我的代码

NSError *error;
NSHTTPURLResponse *response;

NSData *posting =
[NSJSONSerialization dataWithJSONObject:[input createJsonDictionary]
                                options:0
                                  error:&error];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", kURL]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:@"application/json"
  forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:[NSString stringWithFormat:@"AuthToken %@",token]
  forHTTPHeaderField:@"Authorization"];
[urlRequest setHTTPBody:posting];

NSData *urlResponse =
[NSData dataWithData:[NSURLConnection sendSynchronousRequest:urlRequest
                                           returningResponse:&response error:&error]];
NSDictionary *jsonDictionary =
[NSJSONSerialization JSONObjectWithData:urlResponse
                                options:0
                                  error:&error];

NSLog(@"status code: %i", [response statusCode]);

NSLog(@"URL: %@", [urlRequest URL]);
NSLog(@"header: %@ \n method: %@", [urlRequest allHTTPHeaderFields], [urlRequest HTTPMethod]);
NSLog(@"body: %@\n", [[NSString alloc] initWithData:[urlRequest HTTPBody] encoding:NSUTF8StringEncoding]);

在 NSLog 我得到状态码 500,有一个错误。但是当我尝试使用 cURL 执行相同的命令时

curl --request POST -H "Content-Type: application/json" 
-H "Authorization: AuthToken TOKEN" --data '{"DATA"}' -sL 
-w "\\n%{http_code} %{url_effective}\\n" https://URL.com

我返回状态码 201,成功。我的代码似乎有些不对劲。同样在 urlRequest 的 NSLogs 中,它们等于 curl 命令中的内容。有什么我做错了吗?

4

2 回答 2

0

代替

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", kURL]];

尝试

NSString *urlText = [NSString stringWithFormat:@"%@", kURL];
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlText];
于 2012-09-28T15:48:19.187 回答
0

找到了我自己的答案。问题是我的代码正在同步调用服务器,而服务器没有设置为进行同步 Web 调用。相反,我必须使用 NSURLConnection 的即时变量并异步调用“sendAsynchronousRequest:queue:completionHandler:”,并使用方法 start/cancel 和即时变量。

于 2012-10-02T14:14:59.057 回答