iPhone POST request with JSON data - objective-c

I am building my first iPhone application and have run into problems trying to POST json data to my MongoDB database.
This is my code thus far:
NSString *post = [NSString stringWithFormat:#"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://myURL/users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
I get this response in the console:
2014-06-10 16:07:09.758 SocialEyez[2226:70b] Reply: {
"_id": "5397656dd7ec395c1b808230"
}
So even though the POST seems to go through fine, there is something wrong with my formatting which prevents the JSON data from being entered.
I've tried to format the NSString a hundred different ways but nothing seems to work.
Please help me out!!
EDIT:
When I send this request over jQuery:
jQuery.post("http://site/users", { "name": "George Washington", "reputation": "pres", "phone_number": "1234" }, function (data, textStatus, jqXHR) { console.log("Post resposne:"); console.dir(data); console.log(textStatus); console.dir(jqXHR); });
I get the following response:
_id: "53978f4cd7ec395c1b808247"
name: "George Washington"
reputation: "pres"
phone_number: "1234"

This example assumes that the post data should be JSON.
Create the JSON from a dictionary, let NSJSONSerialization add the JSON syntax.
// #"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"
// Create the dictionary
NSDictionary *postDict = #{#"name":#"blah", #"reputation":#"100", #"phone_number":#"1234"};
// Create the JSON data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];
// Just for this example: display the jsonData as an ASCII string
NSLog(#"jsonData as String: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog output:
jsonData: <7b226e61 6d65223a 22626c61 68222c22 72657075 74617469 6f6e223a 22313030 222c2270 686f6e65 5f6e756d 62657222 3a223132 3334227d>
jsonData as String: {"name":"blah","reputation":"100","phone_number":"1234"}

Related

POST form data in Objective C

I have to pass form data in body part. here is postman screen short for better understanding.
body part
content type
here is my code what I had try.
NSString *Accesstoken = [NSString stringWithFormat:#"Bearer %#",tokenInfo.access_token];
// parameter is String object : "user_id=18&deal_id=218"
//NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"user_id", #"18487",
#"deal_id", #"218",
nil];
// NSError *errorr;
// NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&errorr];
[request setValue:Accesstoken forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// NSData *postData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// [request setHTTPBody:postData];;
// [request setHTTPBody:[parameter dataUsingEncoding:NSUTF8StringEncoding]];
// [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:#{#"user_id":#"18487",#"deal_id":#"218" } options:0 error:nil]];
for above code I am getting http status code : 404 its wrong. and when I try in postman I am getting 401 its perfect I want that. Please help Thanks.
Just export the request from POSTMAN in objective-C : https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets

Can't POST a request to service

For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!
It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes
So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.

JSON to NSDictionary from http post request

I created a simple php file to output a JSON String:
<?
$test = $_POST["hashcode"];
if ($ttest != "")
{
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'couponcode' => $test);
echo json_encode($arr);
}
?>
I am trying to use objective-C language to retrieve this json and parse it into a NSDictionary. I am currently using the JSON framework, but it isn't working for me.
NSHTTPURLResponse * response;
NSError * error;
NSString *post = #"hashcode=asdf1234fdsa";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"www.ski-inndronten.nl/json.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *testJSON = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *jsonString = [testJSON JSONRepresentation];
NSLog(#"String = %#",jsonString);
NSDictionary *testDict = [jsonString JSONValue];
NSLog(#"testDict = %#",testDict);
I hope you can help me out since I have no idea what I did wrong. (I am outputting NULL objects)
OK there are two errors:
the first, you forgot to add "http://" in front of your URL string. If you don't do it the request will fail and returned data is nil.
the second, you are sending the incorrect application/json content type, if you do this the php will return an invalid answer. Simply remove this setting and the returned code will be correct.
By the way you can facilitate your debugging by logging the returned data as below:
NSData *testJSON = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",[[NSString alloc] initWithData:testJSON encoding:NSUTF8StringEncoding]);
If you do these two corrections, the answer will be correctly returned.

JSON for Objective-C returns error "Illegal start of token [r]"

I am attempting to connect to a web page and return a JSON string. This string simply needs to be parsed in JSON and returned into an NSArray that I have waiting for it. The problem is that JSON doesn't always return the results. Sometimes, it works well. Sometimes, it returns (null), citing the error below.
self.accounts = nil; // Clear the NSArray
NSString *post = [NSString stringWithFormat:#"username=%#", username.text];
NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]];
// Submit login data
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString: #"http://###.#####.###/app/getaccts.php"]];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody: postData];
// Retreive server response
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
accounts = [[content JSONValue] allValues]; // Parse JSON string into the array
NSLog(#"Array: %#", accounts);
The page I am submitting to returns this:
{"1":"856069060", "2":"856056407"}
JSON logs the following error:
-JSONValue failed. Error is: Illegal start of token [r]
Can I get a little more info ... specifically, I'd like you to check the return value of your sendSynchronousRequest so can you make this change and rerun your test:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (returnData == nil) {
NSLog(#"ERROR: %#", err);
} else {
NSLog(#"DATA: %#", returnData);
}

JSON POST Request on the iPhone (Using HTTP) Problems

Im having problems with my request to a asp .net mvc web service. I read in a thread a while ago that its possible to find out what the server wants the the request's content-type to be etc. I get no error when compiling but when I do the actual request nothing happens and in the log of the server it only says (null) (null). There is no problem doing the GET request and fethcing all objects that are in the list. Can anyone please help me with this irritating bug? here is the code:
//----------------GET request to webservice works fine----------------------------------------
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod: #"GET"];
NSData *response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *stringResponse = [[NSString alloc] initWithData: response encoding: NSUTF8StringEncoding];
//NSLog(#"stringResponse is %#", stringResponse);
//--------------------------------------------------------------------------------------------
NSString *twitterTrendsUrl=#"http://search.twitter.com/trends.json";
NSString *output=
[NSString stringWithContentsOfURL:[NSURL URLWithString:twitterTrendsUrl]];
id theObject= [output JSONValue];
NSLog(#"TWITTER: %#",theObject);
*/
//--------------------------------------------------------------------------------------------
NSURL *url = [NSURL URLWithString:#"http://errorreport.abou.se/Errors/1.0"];
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\"}";
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\",\"Address\":\"smedjegatan\",\"StreetNumber\":\"34\",\"Feedback\":\"True\",\"FeedbackWay\":\"Telefon\"}";
NSMutableDictionary* jsonObject = [NSMutableDictionary dictionary];
//NSMutableDictionary* metadata = [NSMutableDictionary dictionary];
//[metadata setObject:#"NewLoc" forKey:#"Uri"];
//[metadata setObject:#"Location.NewLoc" forKey:#"Type"];
//[jsonObject setObject:metadata forKey:#"__metadata"];
[jsonObject setObject:#"Gurras" forKey:#"Description"];
[jsonObject setObject:#"Klotter" forKey:#"Category"];
[jsonObject setObject:#"smedjegatan" forKey:#"Address"];
[jsonObject setObject:#"34" forKey:#"StreetNumber"];
[jsonObject setObject:#"True" forKey:#"Feedback"];
[jsonObject setObject:#"Telefon" forKey:#"FeedbackWay"];
// ... complete the other values
//
NSString* jsonRequest = [jsonObject JSONRepresentation];
// jsonString now contains your example strings.
NSLog(#"Request: %#", jsonRequest);
//NSURL *url = [NSURL URLWithString:#"https://mydomain.com/Method/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
//[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"returnData: %#", returnString);
I can also add an example of how to talk to the service with javascript:
<script type="text/javascript">
var obj = { "Description": "det kanske funkar" };
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Errors/1.0",
dataType: "json",
contentType: "application/json",
processData: true,
data: '{"Description": "STeffeent asdasd", "Category": "Miljö", "Address": "Bogatan","StreetNumber": "14", "Feedback": "true", "FeedbackWay": "Brev"}',
success: function (data) {
$("#result").text(data.Description);
}
});
});