2

我正在尝试使用我制作的 Sinatra API 从我的 iPhone 发布请求。目前我所有的 Sinatra 应用程序正在做的就是打印发送给它的请求。这是代码:

post '/profile' do

    puts "#{params}"
end

我的objective-c也很简单。它所做的只是向我的 API 发送一个 post 请求:

NSURL *url = [NSURL URLWithString:kBaseURLString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:JSON, @"json", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/profile" parameters:dictionary];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"SUCCESS");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@", error);
}];
[operation start];

当 JSON(在 obj-c 的第 3 行)是一个非常短的字符串时,例如 @"test",Sinatra 会像这样正确地打印出来:

{"json"=>"test"}

当我使用实际的 JSON 配置文件数据时,它是一个非常长的 JSON blob,Sinatra 将其打印出来如下:

{"json"=>"(null)"}

我无法弄清楚为什么长斑点会通过。我 100% 确定我传递了正确的字符串,但 Sinatra 没有收到它。我目前的理论是 Sinatra 对请求有最大字符限制,但我是 Sinatra 和 Ruby 的新手,我不知道如何测试它。出了什么问题?

更新:

首先,感谢 Kjuly 的建议。我发现我在 Sinatra 的字符限制上错了。在 obj-c 中,我正在记录第 3 行具有 JSON blob 的字典,并且它具有 json blob。但是,当我在第 4 行记录 NSMutableURLRequest 的正文时,正文为空。当我使用我的小 JSON blob 时,主体已被填满。

NSMutableURLRequest 有字符限制吗?谁能想到为什么它不接受我的带有大 JSON blob 的非常大的字典,但不接受小字典的原因。

谢谢!

再次更新:

请求正文现在可以正确填写。我不得不将此行添加到第 3 行:

[httpClient setParameterEncoding:AFJSONParameterEncoding];

现在我在 Sinatra 的 HTTPResponse 中得到这个响应:

Error Domain=com.alamofire.networking.error Code=-1016 "Expected content type {(
    "text/json",
    "application/json",
    "text/javascript"
)}, got text/html"

Sinatra 现在只是打印

{}

而不是 {"json"=>"(null)"}

仍然不确定发生了什么。

更新 3

好的,我认为来自 Sinatra 的 HTTPResponse(文本/json 内容)是因为我在 AFNetworking 中从 Sinatra 返回了一个文本/html。我现在检查了 Sinatra 正在接收的主体,我的巨大 JSON blob 在那里。但是,“params”仍然是空的。

有人知道为什么吗?

解决它

看起来当您将 JSON 发布到 sinatra 时,您必须直接阅读请求的正文。在 Sinatra 中,您可以这样做:

profile = JSON.parse(request.body.read.to_s)

然后 profile 是您解析的对象。

4

1 回答 1

1

我认为您需要AFJSONRequestOperation改用,这是一个示例代码:

// Fetch Data from server
NSURL *url = [NSURL URLWithString:@"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation * operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                success:^(NSURLRequest * request, NSHTTPURLResponse * response, id JSON) {
                                                  NSLog(@"Name: %@ %@", [JSON valueForKeyPath:@"first_name"], [JSON valueForKeyPath:@"last_name"]);
                                                }
                                                failure:nil];
[operation start];

或者您可以访问WIKI 页面,请参阅第 4 步:下载和解析 JSON

于 2012-02-20T04:56:03.387 回答