当我通过curl调用时,有一个JSON调用,如下所示:
卷曲-H “Content-Type:application / json”-H “接受:application / json”-d “{\”checkin \“:{\”message \“:\”这是一个 测试\”}}” http://gentle-rain-302.heroku.com/checkins.json
我得到了这个结果:
{ “签入”:{ “created_at”: “2011-01-29T13:52:49Z”, “ID”:3, “消息”:“这 是一个 试验”, “的updated_at”: “2011-01-29T13:52:49Z”}}
但是当我在我的iPhone App中打电话时如下:
- (void)doCheckIn:(NSString *)Str
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"inStore-settings.plist"];
NSDictionary *plistDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
NSString *appURL = [plistDictionary objectForKey:@"apiurl"];
appURL = [appURL stringByAppendingString:@"checkins.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:appURL]];
[request setPostValue:@"{\"checkin\":{\"message\":\"test\"}}" forKey:@"message"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(response);
}
}
我得到一个结果说:
“你想要的改变被拒绝了 (422)“
非常感谢任何帮助。
答案 0 :(得分:2)
查看你的curl命令,我认为你不想做http多部分帖子,ASIFormDataRequest
是专门设置来处理的。您只想将请求的帖子正文设置为您的json字符串。尝试使用普通的ASIHTTPRequest
类,并通过appendPostData:
之类的方法将数据添加到帖子正文中。这应该为您构建适当的HTTP请求。
答案 1 :(得分:1)
这段代码有效:
- (void)doCheckIn:(NSString *)Str
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"inStore-settings.plist"];
NSDictionary *plistDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
NSString *appURL = [plistDictionary objectForKey:@"apiurl"];
appURL = [appURL stringByAppendingString:@"checkins.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:appURL]];
[request appendPostData:[@"{\"checkin\":{\"message\":\"test by Zuzar\"}}" dataUsingEncoding:NSUTF8StringEncoding]];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request addRequestHeader:@"Accept" value:@"application/json"];
[request setRequestMethod:@"POST"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(@"%@", response);
}
}
答案 2 :(得分:-2)
您是否尝试在Accept
个实例中设置Content-Type
和ASIFormDataRequest
标题?