Hi I am sending an http post request to a server the java code i am referring to has a method as set entity in the post request. How can i achieve this in iOS .
I am presently putting the json data to be sent in the body but am getting the error
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
but was
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
my code is
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,#"text",#"Sent",#"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,#"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Add this in your code:- [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Related
I have to make json post request with the following request parameters,
{
"method":"login",
"data":{
"username":"korea",
"password":"123456"
}
}
I use the following code to make the request,
NSString *jsonRequest = [NSString stringWithFormat:#"{""\"\method:\"\login\"\"\,""\data:\"{\"\"username\":\"%#\",\"password\":\"%#\"}",username,password];
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 have to get the response but Im not be able to get the response
Try this
NSDictionary *objectDic = #{#"username" : username, #"password" : password};
NSDictionary *dataDic = #{#"data" : objectDic};
NSDictionary *methodDic = #{#"method" : #"login", #"data": dataDic};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
options:NSJSONWritingPrettyPrinted
error:nil];
[request setHTTPBody: requestData];
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/
I can add an object to an API via JSON when I send the request using byte char[] however it doesn't work when I convert an NSDictionary to NSData and send that. What's the problem here ?
Here's when it works.
// Request
NSURL* URL = [NSURL URLWithString:#"SOME URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
// Headers
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Body
const char bytes[98] = "{\n\t\"user\" :\n\t{\n\t\t\"email\" : \"test#gmail.com\",\n\t\t\"username\" : \"example\",\n\t\t\"password\" : \"cryptx\"\n\t}\n}";
request.HTTPBody = [NSData dataWithBytes:bytes length:98];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
This is when it doesn't work:
- (void)addUser:(User *)user
{
NSURL* URL = [NSURL URLWithString:#"API_URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *data = [self createJSONWithUsername:#"X" andEmail:#"x#X.com" andPassword:#"pass"];
[request setHTTPBody:data];
NSLog(#"%#", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
- (NSData *)createJSONWithUsername:(NSString *)username andEmail:(NSString *)email andPassword:(NSString *)password
{
NSArray *objects = [NSArray arrayWithObjects:password, email, username, nil];
NSArray *keys = [NSArray arrayWithObjects:#"password", #"email", #"username", nil];
NSDictionary *userDataDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *userDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userDataDictionary, #"user", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error:nil];
return jsonData;
}
The second one does not add the user while the second one does.
EDIT
JSON BEING SENT i.e. the jsonString variable
{
"user" : {
"email" : "x#X.com",
"username" : "X",
"password" : "pass"
}
}
This is how I'd do it. It's pretty much exactly what I use in a few apps. I formatted around your provided code...
- (void)addUser:(NSDictionary *)sentuserdetails {
NSURL *url = [NSURL URLWithString:#"SOME URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.timeoutInterval = 30.000000;
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sentuserdetails options:NSJSONWritingPrettyPrinted error:nil]; //don't set error to nil, handle the error
[request setHTTPBody:jsonData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
I am trying to a restful web service in iOS application using NSUrlConnection. I am using below code to format the json string and then send over to a restful web service. But I am getting '415(unsupported media type)' response in connectionReceiveResponse: method. Please tell me where I am going wrong here.
NSURL *urlLoginAuthentication= [NSURL URLWithString:#"http://www.loginService/mp/api"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlLoginAuthentication];
[request setHTTPMethod:#"POST"];
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:self.txtUserName.text, self.txtPassWord.text,nil] forKeys:[NSArray arrayWithObjects:#"username",#"password", nil]];
NSLog(#"Dict: %#",jsonDict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON String: %#",jsonString);
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"contentType"];
[request setValue:#"json" forHTTPHeaderField:#"dataType"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(#"jsonData: %#",jsonData);
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
You receive HTTP status code 415 when the Content-Type you sent with the request is not a support type. Looking at the code, you are incorrectly setting the Content-Type header. This line:
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"contentType"];
should be
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
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];