in iOS to create this
"{
"email":string,
"password":string
}"
json request body, i am passing the nsdata that i create from the string
email=myname#domain.com&password=mypassword
to the setHTTPBody method of the NSMutableURLRequest.This works fine im ok with this.
But what if i want to create this
"{
"post":
{
"title":string,
"room_id":int,
"content":string,
}
}"
json request body? i tried to make some string combinations to solve this recursion but didnt work out really. I also checked the methods of NSMutableURLRequest but i couldnt find something related to solve this.
edit:
This creates the post as it should be its fine, but i need an equivalent to the string email=myname#domain.com&password=mypassword for the recursive case. When i send the data as it should be it does not work. When i send as the string that i provided it works.
NSString *usertoken = [appDelegate token];
NSString *posttopic = #"111testtopic";
NSString *postbody = #"111testbody";
NSDictionary *dict = #{#"post":#{#"title":posttopic,#"room_id":#"246",#"content":postbody}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//send the post
NSString *urlstring = [NSString stringWithFormat:#"http://mydomain.com/posts.json?auth_token=%#", usertoken];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:body];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
Try this
NSDictionary *dict = #{#"post":#{#"title":string,#"room_id":int,#"content":string}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
the idea is to use some nested dictionaries to describe your json and serialize them to get your jsonData to pass to the request.
Related
I'm trying to add a custom header field "jsonParams" to a POST request via addValue like so:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:120.0];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request addValue:jsonString forHTTPHeaderField:#"jsonParams"];
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
[request setHTTPBody:bodyData];
However the "jsonParams" field isn't getting added to the header fields. If I change the value from jsonString to a string object like #"test", though, it works just fine. Any ideas?
Code:
arrValues = [[NSMutableArray alloc]initWithObjects:#"Chennai", nil];
arrKeys = [[NSMutableArray alloc]initWithObjects:#"loc", nil];
dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
NSString *strMethodName = #"agentuserlist";
strUrlName = [NSString stringWithFormat:#"%#%#?filters=%#",appDelegate.strURL, strMethodName, dicValue];
//strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"zyt45HuJ70oPpWl7" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSURLResponse *response;
NSData *received = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(#"error:%#", error);
NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(#"response :%#", strResponse);
I try to send json argument through get method.It gives error as "unsupported url(-1002)".
The URL is working fine when I checked with Postman. I am unable to find out the problem.
Where I went wrong?
I think the problem lies in how you encode your NSDictionary in the NSURL.
You probably want your URL to look like this: http://my domain.com/agentuserlist?loc=Chennai. But the raw encoding of the NSDictionary inside the NSURL doesn't produce this result.
You can follow the accepted answer
from this question to get an idea of how to transform an NSDictionary into a regular list of URL parameters (with proper encoding of dictionary values: don't forget the stringByAddingPercentEscapeUsingEncoding part): Creating URL query parameters from NSDictionary objects in ObjectiveC
I want to create HTTP request post and get response by using simple Objective C Code method. Here below code to I can post successfully. But I didn't receive response data's. Response printing null value only. Please help me, I need to get response data's.
Here below my code
NSString *post = [NSString stringWithFormat:#"name=%#",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:#"response"];
NSLog(#"UPDATE RESPONSE : %#", respon);
You's data post is NSString *post = [NSString stringWithFormat:#"name=%#",name]; . So in this case you need set request header "Content-Type" to "application/x-www-form-urlencoded" or use following code to convert string to data and set Content-Type header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
...
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Its very simple:
//-- Convert string into URL
NSString *jsonUrlString = [NSString stringWithFormat:#"demo.com/your_server_db_name/service/link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Send request to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//-- Send username & password for url authorization
[request setValue: jsonUrlString forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"]; //-- Request method GET/POST
//-- Receive response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
Sample : https://github.com/svmrajesh/Json-Sample
I've been looking into/using web service and I managed to extract and use JSON text from a server. At the moment, Im looking into sending info back, but I've had no luck. In my JSON file I have an array which I would like to add-on to through the use of Xcode. I've tried many things to no avail.
NSError *error;
NSDictionary *jsonDict = #{ #"myArray":#"NewObject"};
NSData* postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:#"url going to JSON file"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[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 based this code on another post, but I clearly don't understand, because its not adding anything to the JSON array. Just to clarify, I want to make it so that the new object that is added stays in the .json file.
EDIT: Since there is a bit of confusion Im posting the JSON code
{
"mykey": "myvalue",
"myarray": [
"one",
"two"
]
}
The objective is so that in the .json file in the "myarray" it would be "one","two","NewObject". The text "NewObject" would be a string that is coming from Xcode . Sorry for not being clear.
I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
and the controller:
public String Post([FromBody]string macAddress)
{
//......
}
(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)
Thanks for the help.
It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"rsdevicetoken"];
NSString *postString = [NSString stringWithFormat:#"token=%#&active=%#&draw=%#&result=%#&message=%#",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", data);
Hopefully this will help you.
It's a wild guess but if your macAddress post param has the following format: 01:23:45:67:89:ab you need to url encode the ':' to '%3A'.