Put JSON data in NSURL

I am trying to do something that seems uninteresting, but for some reason does not work.

I am trying to make a request to receive JSON data by sending the JSON parameter 'data' to the URL.

Here is the code I'm using:

NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys: username, @"username", password, @"password", nil]; NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@", [whatToPost JSONString]]; NSURL *theUrl = [NSURL URLWithString: [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; //NSLog(url) will produce this: http://domain.com/user/get?data={"username":"test1","password":"poop"} 

When I set a breakpoint, Url is null. I can’t understand why this breaks down, but I see something in the package {or "violates it. Any ideas? Should I just switch to POST?

+4
source share
2 answers
 NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys: username, @"username", password, @"password", nil]; NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@", [whatToPost JSONString]]; NSURL *theUrl = [NSURL URLWithString: [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

you switched method

stringByAddingPercentEscapesUsingEncoding:

Returns the representation of the recipient using the specified encoding to determine the percentage screens needed to convert the recipient to the legal URL string.

stringByReplacingPercentEscapesUsingEncoding

Returns a new line, obtained by replacing all percentage screens in the receiver with matching characters defined by this encoding.

cm:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
http://blog.evandavey.com/2009/01/how-to-url-encode-nsstring-in-objective-c.html

+11
source

You should consider sending the HTTP authentication header to the request instead of sending the username and password in the URL itself.

Something like: [request setValue: [whatToPost descripiption] for HTTPHeaderField: @ "Authorization"];

Of course, this assumes that you are in control of the other end of the transaction, i.e. the web service that you click on.

0
source

All Articles