There is a JSON call which when i call via curl like below:
curl -H
"Content-Type:application/json" -H
"Accept:application/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?
Related
Using Postman on my Mac I have confirmed GET/POST works to my endpoint. On my iPad I am trying to do the same thing but only GET connects and returns data (just for
testing).
In Postman I have key of devices and value of [{"name":"1","values":[121,182,243]}]
From Postman I can Send and the physical object responds and the server returns an array of all devices and nothing else (which I do not require but that is how it goes). Postman does have x-www-form-urlencoded under Body. This works as expected from Postman.
From my iPad the following code always returns an error 400 which I think means I am providing something the server is not expecting.
+(void)makeRequest {
NSError *error = nil;
storedURL = [[NSUserDefaults standardUserDefaults] objectForKey:#"eb-ipaddress-saved"];
NSString *urlstring = [NSString stringWithFormat:#"http://%#",storedURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *jsonPostBody = #"{\"devices\":[{\"name\":\"1\",\"values\":[121,182,243]}]}";
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"SUCCESS");
}
else
{
NSLog(#"FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
}
My 4 logs from above (removed for clarity) return:
urlstring http://192.168.90.55:3000/dmx/set
jsonPostBody {"devices":[{"name":"1","values":[121,182,243]}]}
httpResponse 400
Error
I will eventually switch to variables in my POST when in production.
Thank you
Thanks to Larme's answer I used the code from Postman and that worked.
+(void)makeRequest
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.90.55:3000/dmx/set"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSDictionary *headers = #{
#"Content-Type": #"application/x-www-form-urlencoded"
};
[request setAllHTTPHeaderFields:headers];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[#"devices=[{\"name\":\"1\",\"values\":[121,182,243]}]" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
dispatch_semaphore_signal(sema);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"%#",responseDictionary);
dispatch_semaphore_signal(sema);
}
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
I'm having troubles sending a post message to my Wep.api application. I already tried my wep.api on google chrome postman application and it works perfectly. I want my code in the xcode to send this json message to my wep.api
Content-Type: application/json; charset=utf-8
{ UserName: "fjkdlajfka", DeviceID: "1568948" , Password: "fkjdalfda"}
But everytime i send the message, I keep getting null on the parameters. this is my xcode message:
NSString *JsonMsg = [NSString stringWithFormat:#"{UserName: \"%#\",DeviceID: \"%#\",Password: \"%#\"}",
Username.text,#"123456789",Password.text];
NSURL *url = [NSURL URLWithString: #"http://192.168.xxx.xxxx:53913/api/LogIn"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [JsonMsg length]];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[JsonMsg dataUsingEncoding:NSUTF16BigEndianStringEncoding allowLossyConversion:YES]];
conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if ( conn ) {
webData = [NSMutableData data];
}
else {
NSLog(#"theConnection is NULL");
}
Does anyone know whats the error here?
Your JSON is invalid , you are missing quotes
NSString *JsonMsg = [NSString stringWithFormat:#"{"UserName": \"%#\",
"DeviceID": \"%#\",
"Password": \"%#\"}",
Username.text,#"123456789",Password.text];
I would like to send a JSON file from my BB device to my local server. On iOS I used the ASIHttpRequest library and what I did was :
//send json file , using ASIHttpClass
NSURL *url = [NSURL URLWithString:urlStr];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.timeOutSeconds = TIME_OUT_SECONDS;
[request setRequestMethod:#"PUT"];
NSString *credentials= [self encodeCredentials];
[request addRequestHeader:#"Authorization" value:[[NSString alloc] initWithFormat:#"Basic %#",credentials]];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
if([request responseStatusCode]==200){
return true;
} else {
return false;
}
How could I implement the same functionality in my BlackBerry OS < 7.X application?
I am trying to query my Neo4j database, using the REST API.
I have this working so far without using the Cypher query language to retrieve data,
however, now I need to get nodes which are sorted by 'newest' i.e. unix timestamp DESC.
I have tried to add the query within the HTTP body of the NSMutableURLRequest but I am just getting the HTTP error 405.
Here is my code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#node/%i", EventsManagerDataURL, creatorID]];
NSLog(#"Connecting to URL: %#", url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart,'params' : {}}";
NSData *jsonData = [jsonMap dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", jsonData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data){
NSLog(#"%s. Data: %#", _cmd, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(#"Error: %#", error.localizedDescription);
}
}];
You're missing a single quote here:
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart***'***,'params' : {}}";
And actually, it needs to have double quotes:
NSString *jsonMap = #"{\"query\" : \"start x = node(4,6,7) return x order by x.datestart\", \"params\" : {}}";
Test with cURL:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"query" : "start x = node(4,6,7) return x order by x.datestart", "params" : {}}' localhost:7474/db/data/cypher
I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 5. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
// any other things to set in request? or working this way?
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// What to do with NSURLConnection? Or how to send differently?
But I really don't know how to send a JSON object to a server using a POST method at all.
Could anybody please help me out?
I worked it out by trying a bit around, here's my code:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
- (IBAction)txtFetchData2:(id)sender {
NSString *queryString = [NSString stringWithFormat:#"http://example.com/username.php?name=%#", [self.txtName text]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:
queryString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Value1", #"Key1",
#"Value2", #"Key2",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:NSJSONWritingPrettyPrinted error:&error];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// should check for and handle errors here but we aren't
[theRequest setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
//do something with error
} else {
NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
}];
}
NSString *strUrl = #"URL";
NSURL *url = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
// For set postdata in string
NSString *strPatientID = [NSString stringWithFormat:#"%#%#%#%#",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text];
NSString *deviceToken = #"";
postString = [NSString stringWithFormat:#"practiceid=%#&email=%#&password=%#&devicetoken=%#",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken];
NSMutableData *httpDataBody = [NSMutableData data];
[httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *strPostLength = [NSString stringWithFormat:#"%lu",[httpDataBody length]];
if ([httpDataBody length ] > 0){
[request addValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:strPostLength forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:httpDataBody];
}
urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[urlConnection start];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://webstar52.com/demo/webcommunity/work.php"]]];
NSString *post = [NSString stringWithFormat:#"&tag=%#&user_id=%#",#"getcontact",#"10408"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];