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
Related
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'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 want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.
I'm trying to make a POST request using NSURLConnection. I use Charles to debug and Charles every time says that the method is GET. I've tried all different ways and can't get it to work. I am NOT using JSON.
-(void)getList
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://example.com/api/getList"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *radius = #"15";
NSString *latitude = #"-117.820833";
NSString *longitude = #"34.001667";
NSString *parameters = [NSString stringWithFormat:#"longitude=%#&latitude=%#&radius=%#", longitude,latitude, radius];
NSLog(#"PARAMS = %#", parameters);
NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
}
Does anybody know what am I doing wrong? When I access my web service it seems like I'm not posting anything. I'm getting empty response.
Please help with any ideas. I pretty much have to make a simple POST request. Maybe someone can help me debug this better.
If the server is redirecting your request for some reason (perhaps authentication) then the POST information can get lost.
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.