i have this method -
NSArray *objects = [NSArray arrayWithObjects:appDelegate.UserID,itemName.text,#"1",#"1",itemDegem.text,itemDescription.text, nil];
NSArray *keys = [NSArray arrayWithObjects:#"userId",#"itemName",#"itemCategoryId",#"regionId",#"degemName",#"itemDescription", nil];
NSDictionary *registerDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonRequest = [registerDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://www.somedomain.com/method"];
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) {
self.responseData = [NSMutableData data];
}
but when i send strings in my objects that not in english im getting error from the server.
now, i know its a UTF8 problem, but i did set it to be UTF8. can someone please help me figure it out ?
I think the error is strlen([jsonRequest UTF8String]) is not equal to [jsonRequest length].
Use NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; to convert a NSString into NSData using UTF8 encoding.
Related
i have a trouble when i try to call a web service made in WCF, this service is calling by Mac os x app.
this is the code
soapMessage = #"{name:\"Sergio\"}";
NSURL *url = [NSURL URLWithString:#"http://localhost/GSBonoServicios/GSBonoService.svc/HelloWorld"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest setHTTPMethod: #"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *requestData = [NSData dataWithBytes:[soapMessage UTF8String] length:[soapMessage length]];
[theRequest setHTTPBody:requestData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
The connection is successful but didn't a response, i try implementing some tutorials and I'm looking in Stackoverflow and i find many answers but nothing works, i hope you can help me.
ps. I do not speak much English, but I hope I explained, Thanks
Finally I found the solution the problem was in the service, and the code that works is
NSString *name=#"Sergio";
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys: name, #"name",
nil];
NSURL *url = [NSURL URLWithString:#"http://www.myserver.com/Servicio/ServicioEjemplo.svc/HelloWorld"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod: #"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"applicat ion/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:kNilOptions error:&error];
[theRequest setHTTPBody:postdata];
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:postdata
encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Thanks
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.
I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
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:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
I'm trying to send JSON post using NSURLConnection:
NSURL *url = [NSURL URLWithString:urlStr];
NSString *jsonPostBody = [NSString stringWithFormat:#"{\"user\":""\"%#\""",\"pass\":""\"%#\""",\"listades\":\"\"}",
[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"JSNON BODY:%#", jsonPostBody);
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setTimeoutInterval:2.0];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:#"%d", [postData length]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
App execution gets freeze when it reaches connection command, despite timeout.
I'm stucked in this issue and I can not find a solution.
Many thanks
-(void) jsonRESTWebServiceMethod:(NSString*)method WithParameter:(NSMutableDictionary*)params{
self.iResponseType = JSONTYPE;
NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:method,#"name",params,#"body",nil,nil];
NSData *data = [[CJSONSerializer serializer] serializeObject:bodyDict error:nil];
NSString *strRequest = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
strRequest = [NSString stringWithFormat:#"json=%#",strRequest];
NSData *body = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString *strURL = [NSString stringWithString:WebServiceURL];
NSString* escapedUrlString = [strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
NSString *msgLength = [NSString stringWithFormat:#"%d",strRequest.length];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
if (mydata) {
[mydata release];
mydata = nil;
}
conections = [[NSURLConnection alloc] initWithRequest:request delegate:self];
mydata = [[NSMutableData alloc] init];
}
It's freezing your app because you have passed YES into startImmediately. This will freeze the app until request is finished.
You need to use something like connectionWithRequest:delegate: - this will run the request in the background and tell you when it's done.
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I'm trying to post to a rails backend from Objective-C and JSONKit and am having difficulty getting my results published. I keep getting back a null recordset from my server.
[dictionary setValue:(#"bar") forKey:#"foo"];
NSString *JSON = [dictionary JSONString];
NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: myUrl];
NSString *postLength = [NSString stringWithFormat:#"%d", [theData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSError *error = NULL;
NSURLResponse *response = nil;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json-rpc" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:theData];
NSData *result = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(resultString);
Is there something I'm missing? the JSON seems to be serializing correctly
{"foo":"bar"}
Any help would be greatly appreciated.
Thanks!
Just changed the setValue from json-rpc to json and it worked like a champ.
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
**[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];**
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setHTTPBody:theData];