iOS -post data to java jersery jax-rs web service - ios

hi im implementing a iOS app which post data to RESTFul web-service implemented in java jersey.
iOS code:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"Chris", #"name", #"99", #"age", nil];
NSData * JsonData =[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"%#",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://localhost:8080/testwebservice/submit"]]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
// Handle the success
NSLog(#"Server Response :%#",response);
}
}
];
Java Jersey code:
#POST
#Path("submit")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void postMultivaluedName(MultivaluedMap<String, String> aFormParams) {
System.out.println("postMultivaluedName");
System.out.println("Name is " + aFormParams.get("name"));
System.out.println("Age is " + aFormParams.get("age"));
}
The problem i'm facing is that the value of name and age received on web service is null.
however, if i modify iOS to use this code, it works:
NSString *postString = #"name=chris&age=99";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
So how can i modify my java Jersey to accept NSData using NSDictionary?
While debugging, i also notice that jsonString is actually having #"{\n "name":"chris" \n "age":"99" \n }. is it suppose to have \n in the string?

i managed to solve it. The reason why the following code works is because i set the http content type to application/x-www-form-urlencoded:
NSString *postString = #"name=chris&age=99";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
instead, set the content-type to application/json; charset=utf-8

Related

"+" replaced by " " in json send to server

NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
stringForKey:#"AuthToken"];
NSString* json =[NSString stringWithFormat:#"{'DeviceId':'%#','DeviceType':'iOS','UM_Identifier':'%#','AuthToken':'%#','Query':'all'}", deviceId, userEmail, AuthToken];
NSString *post =[[NSString alloc] initWithFormat:#"jinpAllCustDetails=%#",json];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
In above code :
Auth token received from last webservice response is saved in NSUserdefaults,
then used for next webservice request.
So for Eg.
Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=
But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=
ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.
Help me to fix this, thanks in advance
That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:
NSDictionary *values = #[
#"DeviceId": deviceId,
#"DeviceType": #"iOS",
#"UM_Identifier": userEmail,
#"AuthToken": authToken,
#"Query": #"all"
];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
options:0
error:&error];
NSAssert(jsonData != nil, #"Failed to create JSON data");
NSString jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];

Difficulty receiving JSON from GET request using NSURLConnection

I'm having a hard time trying to receive JSON form a NSURLConnection request. Can anybody offer any advice? I can't understand why the JSON does not appear
EDIT: When I append the endpoint /books to the end of the url string I get this JSON response: " json NSDictionary * 0 key/value pairs. " Does this mean that there is nothing in the server?
-(void)makeLibraryRequests
{
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //;]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[request setHTTPMethod:#"GET"];
// This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//parse data here!!
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (json) {
//NSArray *allBooks = [json objectForKey:#"books"];
//create your MutableArray here
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else{
NSLog(#"error occured %#", jsonError);
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"\n\nError:\n%#\n\nServer Response:\n%#\n\nCrash:", jsonError.description, serverResponse);
//[NSException raise:#"Invalid Data" format:#"Unable to process web server response."];
}
}];
}
As YiPing pointed out, you must provide the books end point. But you won't have anything there until you first post a book.
NSDictionary *params = #{#"author": #"Diego Torres Milano",
#"categories" : #"android,testing",
#"title": #"Android Application Testing Guide",
#"publisher": #"Packt Publishing",
#"lastCheckedOutBy": #"Joe"};
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxaa56/books/"]; // your id removed for security's sake ... put it back in
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *encodeError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&encodeError];
NSAssert(body, #"JSON encode failed: %#", encodeError);
request.HTTPBody = body;
So, first POST a book using a request like the above, then your original GET (assuming you add the end point) will now return a result.
Add some endpoints to your URL
try this:
http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56/books/

iphone json web-services post data

I am working on one iOS Application, in which i need to post the json web-data to web-service url & base of that i need to get response from server side.
as i have tried to code to send the web-data with json formate but unfortunately yet i haven't got any help to make that possible.
below is the web-url & json request data which i need to pass on web-services to get response,
WebUrl : http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios
web data pass : webdata={"device_token":"test"}
now i am confused how i can pass webdata={"device_token":"test"} json post to get response from server side.
below is my code which i have tired to make that possible,
Coding:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *postURL = [NSURL URLWithString: #"http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"Akash IOS PUSH", #"device_token",
nil];
// NSString *string_val = #"webdata=";
// NSString *data = [NSString stringWithFormat:#"data=%#",[[NSString alloc] initWithData:jsData encoding:NSUTF8StringEncoding]];
// NSString *myString_VAL =[NSString stringWithFormat:#"%#%#",string_val,jsonDict];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"content-type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
// Handle the success
NSLog(#"Server Responce :%#",response);
}
}
];
Please any body help me to make this possible.
You can use following code.I hope this may work.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys: #"Akash IOS PUSH", #"device_token",nil];
NSData * JsonData =[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"%#",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://testing.com/controllogic/webservices/all_data_webservice/set_device_token_ios"]]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
// Handle the success
NSLog(#"Server Response :%#",response);
}
}
];

send JSON Object Request to Server

Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

How to send request with XML

I want to send XML file to http://api.online-convert.com/queue-insert
I'm using such code:
NSString *urlString = [NSString stringWithFormat:#"http://api.online-convert.com/queue-insert"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:#"text/xml"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"<queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<apiKey>32423sda..2134</apiKey>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<targetType>audio</targetType>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<targetMethod>convert-to-flac</targetMethod>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<testMode>true</testMode>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"</queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
}
But I always get error:
<queue-answer>
<status>
<code>8</code>
<message>The XML file is empty</message>
</status>
</queue-answer>
Where is my fault? Please help..
I'm sending XML-file in the following way:
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
url = [NSURL URLWithString:#"https://site.ru/request"];
request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
LOG([NSString stringWithFormat:#"Post message: %#"], message);
[message release];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
You probably do not know what you're doing. In the string:
[postBody appendData:[[NSString stringWithFormat:#"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
You are supposed to send the URL to the server where your original file (the file you wish to convert) is located. The link in your code leads to non-existing file.
This piece of code works for me:
- (IBAction)startSOAP:(id)sender
{
NSLog(#"\n{AppDelegate} startSOAP start");
// create the request
NSError **myError;
NSHTTPURLResponse **serverResponse;
NSData *serverData;
NSDictionary *headerFieldsDict = [NSDictionary
dictionaryWithObjectsAndKeys:#"Apple iPhone",#"User- Agent",
#"text/xml; charset=utf-8", #"Content-Type",
#"soapAction",#"SOAP_ACTION",nil];
#try {
// 1) The Request String.
// Note: smsXMLString contains the entire SMS SOAP envelope, without the <? XML declaration command >.
NSString *smsXMLPath = [[NSBundle mainBundle] pathForResource:#"sms" ofType:#"xml"];
self.smsXMLString = [NSString stringWithContentsOfFile:smsXMLPath encoding:NSUTF8StringEncoding error:myError];
// -----------------------
// 2) Create the request.
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theServerURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
// -----------------------
// 2a) Modify the Request from default 'GET' to 'POST':
[theRequest setHTTPMethod:#"POST"];
// 2b) Modify the Headers:
[theRequest setAllHTTPHeaderFields:headerFieldsDict];
// 2c) Sent the Contents of the Body to the SOAP/XML data:
[theRequest setHTTPBody:[self.smsXMLString dataUsingEncoding:NSUTF8StringEncoding]];
// -----------------------
// 3) Get Synchronous Data:
serverData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:serverResponse
error:myError];
// -----------------------
// 4) Convert Synchronous Data into Human-Readable String (Unicode 8) format:
NSString *serverDataString = [[[NSString alloc] initWithData:serverData encoding:NSUTF8StringEncoding] retain];
[[soapResponse layoutManager]replaceTextStorage:[[NSTextStorage alloc] initWithString:serverDataString]];
[serverDataString release];
}
#catch (id e) {
NSLog(#"\n**** {startSOAP} EXCEPTION: %# ****\n",e);
self.statusLine.stringValue = [NSString stringWithFormat:#"*** Exception flagged: %# ***",e];
}
#finally {
NSLog(#"\n{startSoap} end.");
}
}

Resources