I am using URLs downloaded from the Internet, so I don't know their format in advance and they are dynamic.
How to know if I should encode an URL at run time?
// `url` is retrieved from the Internet at run time
// When should I call following line?
let urlString = url!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
If it's already encoded, calling stringByAddingPercentEncodingWithAllowedCharacters will make the URL invalid.
Use:NSString *unencodedUrlString = [originalURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; to decode the URL. Now compare the decoded version with the original. If they are the same, the url is not encoded, otherwise it is already encoded.
Related
On the client side I am reading an image file and encoding it in base64, sending it to as an URL param.
img = open("file.png", "rb").read()
print len(img)
img = img.encode("base64")
print len(img)
print len(img.decode("base64"))
Prints 252235, 340742 and 252235.
On server side decoding the received str couldn't yield the same result. I am posting the encoded base64 as "http://url.com/test?image=img_str".
img = flask.request.args["image"]
print len(img)
img = img.decode("base64")
print len(img)
Prints 340742 which is perfectly fine and 248176 which should actually be the original length. Is image param modifying during the post request? How to do this without using files param in requests or any other solution.
So, I figured this out!
While sending the encoded string as an URL parameter, "+" in the string are converting into " ". So, had to encoded_base64.replace(" ", "+") before decoding. And it worked!
I am getting url from my server response as:
https://baseURL/The+Man+in+the+High+Castle+Official+Trailer+%E2%80%93+2+th.m3u8
and i am doing encoding as :
videoURL = videoURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
but avplayer not able to play this particular url .
seems like some issue in encoding URL
Your URL is already percent-encoded.
If you encode it again, the percent parts will be encoded twice, giving an invalid URL.
You can see that by removing the percent encoding from your URL and setting it again:
let base = "https://baseURL/The+Man+in+the+High+Castle+Official+Trailer+%E2%80%93+2+th.m3u8"
let decoded = base.stringByRemovingPercentEncoding!
print(decoded)
let encoded = decoded.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!
print(encoded)
Am trying to hit a GET service with search keyword as "R+Co", provided in the URL. But the service is receiving as "R Co" which is affecting the search logic. Can we read this as '+' itself in the service?? Thanks in Advance!!
Edit : The service is called from iOS.
In iOS you can encode the url string into UTF8 as
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Use URL Encoding while making GET request.
See link
Encode the query String parameter which is your search keyword.
URLEncoder.encode("R+Co","UTF-8");
This can be escaped using character set using ASCII Encoding Reference. For '+' we can use '%2B'. Now 'R+Co' is read as it is and the service is hit with 'R%2BCo'.
I am trying to set the URL parameters here when doing a post to a REST API and for some reason, they are not appearing on the URL when the request is made.
I have seen the other questions posted, but they only set body parameters, I need to supply application key and session id on URL
// return URLRequestConvertible and NSData
var urlParams:[String: String] = Dictionary()
urlParams.updateValue(ACS_API_KEY, forKey: "key")
urlParams.updateValue(SESSION_ID, forKey: "_session_id")
// cannot figure out how to set params on URL
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: urlParams).0, uploadData)
My best guess here is that you are not using a GET, HEAD or DELETE HTTP method in mutableURLRequest. If it is any of the others, then Alamofire will automatically encode the parameters into the HTTP body of the request. For more information, refer to the encode method under the URL case.
As a workaround, you could set the mutableURLRequest to a GET, run the encode method, then apply the URL to a new request. I realize this is a bit of an odd workaround, but it is necessary since your usage case is not the common one that the ParameterEncoding enumeration was designed for.
Hopefully that helps shed some light.
I have to pass JSON dictionary as POST data to a Webservice. One key involves an Amazon S3 URL string.
The sample request json which works has the URL as....
https:\/\/myappbucket.s3.amazonaws.com\/2014230407_102323.jpg?response-content-type=image\/png&Signature=123456%3D&Expires=139756222548&AWSAccessKeyId=ABCDEF
Notice the backslashes just before the forwardslashes? I have never seen a URL like that, but thats how I'm supposed to pass it.
I tried
stringByAddingPercentEscapesUsingEncoding
and
stringByReplacingPercentEscapesUsingEncoding
while using NSASCIIStringEncoding and NSUTF8StringEncoding
Can anyone make sense of this?
if we try to convert url into legal url trough stringByAddingPercentEscapesUsingEncoding than it adds all percent escapes necessary to convert the receiver into a legal URL string.Uses the given encoding to determine the correct percent escapes.
if we use stringByReplacingPercentEscapesUsingEncoding than it replaces all percent escapes with the matching characters as determined by the given encoding.
mostly to get valid url, we can use NSUTF8StringEncoding to remove backslashes just before the forwardslashes in url.
Generally, you should use a JSON serializer library (e.g. NSJSONSerialization) in order to obtain a JSON from a JSON representation and not try to create the JSON yourself.
A JSON representation is a NSDictionary or NSArray object containing other objects which recursively represent your JSON. Your URL will be represented as a NSString.
What you need to do is simply have a valid URL as a NSString, properly encoded according RFC 3968 and assign it the JSON representation, e.g.:
NSURL* url = ...;
NSDictionary* jsonObject = #{#"url": [url path]};
Now, you can serialize the JSON representation to a JSON:
NSError* error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonObejct
options:0
error:&error];
That's it, and you don't bother how the JSON encoded string looks like (encapsulated in the NSData object as a UTF-8 character sequence).
Purposefully, when you POST this JSON, you SHOULD specify a corresponding request header:
ContentType: application/json
which lets you just use the JSON data as body data as is:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
request.HTTPBody = jsonData;
Side note: [url path] returns a URL as a string according RFC 1808 which is obsoleted by RFC 3968 since January 2005 already. Today, there are newer APIs since iOS 7.0, see NSURLComponents.