There is a JSON call which when i call via curl like below:
curl -H "Content-Type:application/json" -H "Accept:applica开发者_开发百科tion/json" -d "{\"checkin\":{\"message\":\"this is a test\"}}" http://gentle-rain-302.heroku.com/checkins.json
I get this result:
{"checkin":{"created_at":"2011-01-29T13:52:49Z","id":3,"message":"this is a test","updated_at":"2011-01-29T13:52:49Z"}}
But when i call in my iPhone App like below:
- (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);
}
}
I get a result saying :
"The change you wanted was rejected (422)"
Any help is highly appreciated.
Looking at your curl command, I don't think you want to be doing http multipart post, which the ASIFormDataRequest
is specifically set to handle. You just want to set the post body of a request to your json string. Try using the normal ASIHTTPRequest
class and adding data to the post body via a method like appendPostData:
or the like. This should build the appropriate HTTP request for you.
This piece of code worked:
- (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);
}
}
Did you try setting the Accept
and Content-Type
headers in your ASIFormDataRequest
instance?
精彩评论