JSON POST Request on the iPhone (Using HTTP) Problems - objective-c

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);
}
});
});

Related

iMessage bubble calling web service freze the view

i am using iMessage bubble to create chat view working fine
https://github.com/kerrygrover/iMessageBubble
When i call my web service in my inside method this at end
- (IBAction)sendMessage:(id)sender
here is my web method calling function which gives result out put success and send my chat to the server, but my view freeze.
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
}
plz create a new queue not run this code on main queue . you are running the code on main queue plz use this
dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(myQueue, ^{
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
});

Posting JSON data to server

I am trying to post and JSON data to server.
My JSON is:
{
“username”:”sample”,
“password” : “password-1”
}
The way I am sending it to server is:
NSError *error;
NSString *data = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(#"resposne dicionary is %#",responseDictionary);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
The JsonData that is created is a valid JSON accepted by the server.
But the app is crashing and the error is:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0
what is wrong that i am doing here?
I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.
-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#", action];
NSLog(#"%#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
You can easily call it:
- (void) login:(NSDictionary *)data
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placePostRequestWithURL:#"yourActionUrl"
withData:data
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (!(code >= 200 && code < 300)) {
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
NSLog(#"OK");
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
string, #"id",
nil];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
And finally, you invocation:
NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, #"username",
_textFieldPasssword.text, #"password", nil];
[self login:dataToSend
calledBy:self
withSuccess:#selector(loginDidEnd:)
andFailure:#selector(loginFailure:)];
Don't forget to define your callbacks:
- (void)loginDidEnd:(id)result{
NSLog(#"loginDidEnd:");
// Do your actions
}
- (void)loginFailure:(id)result{
NSLog(#"loginFailure:");
// Do your actions
}
First you create an NSString* that is supposed to contain JSON data. This doesn't work in general if the username and password contain any unusual characters. For example, I make sure that I have a quotation mark in my password to make sure that stupid software crashes.
You turn that string into an NSData* using ASCII encoding. So if my username contains any characters that are not in the ASCII character set, what you get is nonsense.
You then use the parser to turn this into a dictionary or array, but store the result into an NSData. Chances are that the parse fails and you get nil, otherwise you get an NSDictionary* or an NSArray*, but most definitely not an NSData*.
Here's how you do it properly: You create a dictionary, and then turn it into NSData.
NSDictionary* dict = #{ #"username": _textFieldUserName.text,
#"password": _textFieldPasssword.text };
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
That's it.
try this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"My URL"];
if (!request) NSLog(#"Error creating the URL Request");
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];

JSON parsing is sending error message in iOS 7.1

I checked my code but not getting what is wrong with my code..I am working on JSON Parsing using post method.this same code is working in Xcode 5 but it is not working in Xcode 6.Getting Bellow error in my JSONSerialization.
parsingResultLogin = {
"error_code" = "-1";
"error_message" = "";
}
My code is -
-(void)loginFromServer
{
NSString *strURL = [NSString stringWithFormat:#"%#login",GLOBALURLDOMAIN];
NSLog(#"strURL =%#",strURL);
NSData *dataPostLogin = nil;
NSDictionary *dicPostDataLogin = [ NSDictionary dictionaryWithObjectsAndKeys:#"qwertyuiopwqq",#"username",#"qwertyuiop",#"password",#"1234567890987654",#"device_token",#"ios",#"device_type", nil];
NSLog(#"%#",[dicPostDataLogin description]);
dataPostLogin = [NSJSONSerialization dataWithJSONObject:dicPostDataLogin options:NSJSONWritingPrettyPrinted error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
NSLog(#"request = %#",request);
[request setHTTPBody:dataPostLogin];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)[dataPostLogin length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"JSON/application" forHTTPHeaderField:#"Content-Type"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"responsedata =%#",responseData);
if (responseData == NULL) {
AppDelegate *appdel = [[UIApplication sharedApplication]delegate];
[appdel alertError];
}
else
{
NSDictionary *parsingResultLogin = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"parsingResultLogin = %#",parsingResultLogin);
//NSString *strParseDataResult = [parsingResultLogin objectForKey:#""];
}
}
Key/values in JSON are separated by ":", not "=". And there should be no semicolon at the end. So this isn't valid JSON and isn't going to parse with a JSON parser.

iPhone POST request with JSON data

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"}

Sending JSON through POST not working - Objective C

I am sending a JSON string to our server using the POST method. What should happen is that it should return a response showing "Array(JSON String) Array(JSON String)". The response contains two arrays: The first array is populated if I used the POST method, while the second array is populated if I use the GET method. I tried sending the JSON through GET method and indeed, the second array was populated. However, when I tried to send JSON through POST method, both arrays are returned empty.
Here is the code I used:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:sqlArray options:NSJSONWritingPrettyPrinted error:&error];
NSURL *url = [NSURL URLWithString:#"http://myurl/xmlrpc/imwebsrvcjson.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSData *result =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if (error == nil){
NSLog(#"The Result string: %#", returnString);
}
Can you tell me what is wrong with my code?
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
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:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.