1

我在使用 RestKit 0.2 做一个简单的帖子时遇到了一些问题。这就是我的代码的样子:

RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromArray:@[@"title"]];

RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[Feed class] rootKeyPath:@""]

NSURL *baseURL = [NSURL URLWithString:@"http://some.url.com"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];

[client setDefaultHeader:@"Accept" value:RKMIMETypeJSON];

RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];

[objectManager addRequestDescriptor:requestDescriptor];

Feed *feed = [[Feed alloc] init];
feed.title = @"SomeTitle";

[objectManager postObject:feed path:/feeds parameters:nil success:nil failure:nil];

当我运行上面的代码时,我得到以下日志:

request.headers={
    Accept = "application/json";
    "Accept-Language" = "sv, en, nl, fr, de, ja, it, es, pt, pt-PT, da, fi, nb, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8";
    "Content-Type" = "application/x-www-form-urlencoded; charset=utf-8";
    "User-Agent" = "appName/1.2 (iPhone; iOS 5.1.1; Scale/2.00)";
}
request.body=[title]=Foobar
2013-02-13 12:05:55.450 appName[3672:330f] T restkit.network:RKHTTPRequestOperation.m:177 POST 'some.url.com' (400 Bad Request) [0.5037 s]:
response.headers={
    Connection = "keep-alive";
    "Content-Length" = 99;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Wed, 13 Feb 2013 11:05:55 GMT";
    "Set-Cookie" = "cookieTextHere; domain=.some.domain.com; path=/; expires=Wed, 27-Feb-2013 11:05:55 GMT; HttpOnly";
    "X-Request-Id" = xxe131e73e638733519c44xxa6224aa3f2xx;
}
response.body={"title":"JSON Parser Error","errors":
"lexical error: invalid string in json text. [title]=Foobar"}

REST 服务器需要 JSON 格式的帖子,但是当我查看上面的日志时,我看到请求的内容类型设置为“application/x-www-form-urlencoded”——这是导致问题的原因吗?我尝试使用

[client setDefaultHeader:@"Content-Type" value:RKMIMETypeJSON];

......但这没有用。

我已经使用 www.hurl.it 将原始 json 数据(如 {"title":"Foobar"} )发布到 url,没有任何问题。

有任何想法吗?

4

1 回答 1

0

布莱克沃特斯已回复google 组的 restkit

以下是我的实现:

  1. 来自 RKManagedObjectRequestOperation 的子类,如果你是 ManagedObject。

EPObjectRequestOperation.h

#import <RestKit/RestKit.h>

@interface EPObjectRequestOperation : RKManagedObjectRequestOperation

@end

EPObjectRequestOperation.m

#import "EPObjectRequestOperation.h"

@interface EPObjectRequestOperation ()

@property (nonatomic, strong, readwrite) NSError *error;
@end

@implementation EPObjectRequestOperation

- (void) main
{
    [super main];
    if([self.HTTPRequestOperation hasAcceptableStatusCode] && self.error.code == -1016) {//Expected content type

        self.error = nil;
    }
}
@end

2.在RKObjectManager上注册子类

[objectManager registerRequestOperationClass:[EPObjectRequestOperation class]];
于 2013-03-11T16:07:24.470 回答