To get the JSON I was using this answer SBJsonWriter Nested NSDictionary
Now I have a sting {"key1":"bla1","key2":{"a":"a1","b":"b1","c":"c1","d":"d1"},"key3":"bla3"} that I've called theString
and I need to add it to a url http://mysyte.net:8888/JSON?
and to receive something like this http://lcwebtest.sytes.net:8888/JSON?{"key1":"bla1","key2":{"a":"a1","b":"b1","c":"c1","d":"d1"},"key3":"bla3"}
Here is what I do:
NSString *urlString = [NSString stringWithFormat:#"http://mysyte.net:8888/JSON?%#",theString];
NSLog gives http://mysyte.net:8888/JSON?{"key2":{"d":"d1","b":"b1","c":"c1","a":"a1"},"key1":"bla1","key3":"bla3"}
Then I make a url from it by
NSURL *url1 = [NSURL URLWithString:urlString];
BUT NSLog(#"%#",url1); gives me {null}
I assume NSURL does not want to read the "{" or "}" and thinks that the url was malformed.
How can I receive the url to make a GET request?
I assume NSURL does not want to read the "{" or "}" and thinks that the url was malformed.
That's right, you're not allowed to put some special characters in a URL. You want to escape the JSON string like this:
CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)theString, // (__bridge CFStringRef)theString if you use ARC
CFSTR(""),
CFSTR("?&=%,:+-"),
kCFStringEncodingUTF8
);
NSString *urlString = [NSString stringWithFormat:#"http://mysyte.net:8888/JSON?%#", (NSString *)escaped];
CFRelease(escaped);
Related
I dont know why but when I am calling the following URL
it gives me BAD REQUEST - INVALID URL, although this URL is working fine on safari browser and other browsers as well
http://www.ysl.com/wx/shop-product/women/top-handles#{"ytosQuery":"true","department":"handbags_tophandle_w","gender":"D","brand":"","macro":"","micro":"","season":"A,P,E","color":"","size":"","site":"","section":"","sortRule":"","yurirulename":"searchwithdepartment","microcolor":"","agerange":"","macroMarchio":"","page":"2","productsPerPage":"50","modelnames":"","look":"","washtype":"","fabric":"","prints":"","suggestion":"false","suggestionValue":"","material":"","occasion":"","weight":"","gal
I am using following code:
NSString *str = [NSString stringWithFormat:#"%#",[payload stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString* webStringURL = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
webStringURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *payload = [NSURL URLWithString:webStringURL];
Any Help Guys? What is that I am doing wrong?
Don't use stringByReplacingPercentEscapesUsingEncoding: on the hole URL, but just on the GET parameters.
Now http:// will also be escaped, thus becoming http%3A%2F%2F which is not valid as an URL.
I have an NSString path to my Documents folder.
NSString* stringURL = #"/var/mobile/Applications/5667FADC-F848-40CF-A309-
7BFE598AE6AB/Library/Application Support/MyAppDirectory";
When I cast it to NSUrl with
NSURL* url = [NSURL fileURLWithPath:stringUrl];
and NSLog(#"Created URL: %#",url);, i get some strange result:
///var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application㤈㤋ތȀ乽啓汲唠䱒›楦敬⼺⼯慶⽲潭楢敬䄯灰楬慣楴湯⽳㘵㜶䅆䍄䘭㐸ⴸ〴䙃䄭〳ⴹ䈷䕆㤵䄸㙅䉁䰯扩慲祲䄯灰楬慣楴湯㈥匰灵潰瑲䴯䅹灰楄敲瑣牯⽹upport/MyAppDirectory/
Why is this so ?
What am I doing wrong ?
I didn't see any Chinese character when I log the value.
NSString* stringURL = #"/var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application Support/MyAppDirectory";
NSURL* url = [NSURL fileURLWithPath:stringURL];
NSLog(#"%#",url);
Classical mistake. Don't use NSLog (url), use NSLog (#"%#", url). The first argument to NSLog is a format string, and % characters in format strings are interpreted, not printed. For example, %s in a format string means another C-String is expected in the argument list. Since url could contain all kinds of characters, this is likely to lead to rubbish results or even crashes.
Based on the answer you accepted from a previous question; it's because the use of stringByAddingPercentEscapesUsingEncoding will generate a printf-like formatting string containing %20S (the space between Application Support is converted to %20), which confuses NSLog():
NSURL *url = [NSURL fileURLWithString:[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] isDirectory:YES];
NSLog(url);
use NSLog("#%", url) to avoid this error.
I have a UISearchBar from which I'm extracting the text that represents an address and building from it a JSON URL for Google Geocoder.
NSString* address = searchbar.text;
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", address];
If I copy & paste the url from debug window to the browser it works like a charm but when I try to convert it to NSURL i get nil
NSURL* theUrl = [NSURL URLWithString:url];
Any ideas?
I added the encoding to the address prior to concatenating the url and that fixed the problem so now the code looks like this:
NSString* address = searchbar.text;
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, CFBridgingRetain(address), NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8));
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", encodedString];
I tried to pass these characters to server, for example *()$
I have coded the NSUrl this way:
NSString *partialURL = [NSString stringWithFormat:#"/%#", commentBody];
NSString *fullURL = [NSString stringWithFormat:#"%#%#", CONST_URL, partialURL];
NSString *encStr = [fullURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encStr];
But then, the commentBody passed in the url still has *()$ things and not encoded into utf8.
What is the correct way to do it?
Thanks!
NSString * test = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)validUrl,
NULL,
(CFStringRef)#";/?:#&=$+{}<>,",
kCFStringEncodingUTF8);
UPDATE
Hi #Rendy. Sorry for the quickie reply yesterday. I only had time to past a 1-liner before jumping off and had hoped it would be enough for you to correct the issue you were having.
You always want to encode the parameters of the URL. IF you have a URL that is a parameter to another URL or embedded in some XML; you'll want to encode the entire url (which means parameters get double-encoded - because you take a "valid" URL and escape it so it becomes a valid parameter in another URL (ie, : and & get escaped, so parameters don't mix together.)
If you like, you can add additional chars to the string below and they'll be replaced with percent-encoded values. I believe the string below already has you covered for the invalid values.
Here's a category on NSString:
#implementation NSString (encode)
+ (NSString*)stringEncodedAsUrlParameter:(NSString *)string
{
NSString *newString = NSMakeCollectable(
[(NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef)string,
NULL, /* charactersToLeaveUnescaped */
CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"),
kCFStringEncodingUTF8
) autorelease]
);
if (newString) {
return newString;
}
return #"";
}
- (NSString*)stringByEncodingAsUrlParameter
{
return [NSString stringEncodedAsUrlParameter:self];
}
#end
Call it like this:
NSString * escapedParameters = [NSString stringEncodedAsUrlParameter:unescapedParameters];
Or:
NSString * escapedParameters = [unescapedParameters stringByEncodingAsUrlParameter];
Then add your properly escaped parameters to the end of your URL. If you encode the whole URL, you'll encode the "http://" portion and it won't work.
I originally copied the above from ASIHttpRequest, but any bugs added are mine.
Hope that helps! Best of luck!!
I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";