Java - Convert String to valid URI object
You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery
in Apache commons-httpclient project
Like this (see URIUtil):
URIUtil.encodeQuery("http://www.google.com?q=a b")
will become:
http://www.google.com?q=a%20b
You can of course do it yourself, but URI parsing can get pretty messy...
Convert String to Uri
You can use the parse
static method from Uri
//...
import android.net.Uri;
//...
Uri myUri = Uri.parse("http://stackoverflow.com")
Converting string to URI
You can use the new URI(string)
constructor (for an URI) and the new URL(string)
constructor for a URL
.
But that won't work with a FileReader
- it requires the URI scheme to be file:
If you want to read a remote file, you need something like:
Reader reader = new InputStreamReader(new URL(urlString).openStream(), encoding);
The encoding can be taken from HttpURLConnection
obtained by url.openConnection()
, but you can also set it to something specific if you know it in advance. (Btw, In the above example I've omitted all I/O resource management)
Note (thanks to @StephenC): the url string must be a valid URL, which means it must start with http://
Convert Uri to String and String to Uri
I need to know way for converting uri to string and string to uri.
Use toString()
to convert a Uri
to a String
. Use Uri.parse()
to convert a String
to a Uri
.
this code doesn't work
That is not a valid string representation of a Uri
. A Uri
has a scheme, and "/external/images/media/470939"
does not have a scheme.
Convert string to its URL representation in Spring Framework
Enhancing example from this answer, you could do it like this:
import java.text.Normalizer;
import java.util.regex.Pattern;
public class UrlifyString {
public static String deAccent(String str) {
String norm = Normalizer.normalize(str, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(norm).replaceAll("").replace(" ", "-").toLowerCase();
}
public static void main(String[] args) {
System.out.println(deAccent("Majstrovstvá v ľadovom hokeji"));
}
}
Output is:
majstrovstva-v-ladovom-hokeji
One thing to note is that it's a lossy conversion so there's no way to go back from this "simplified" form to the original version. Because of this you should not use this as a key to any of the resources, I'd suggest including a unique identifier to the articles, something like:
http://example.com/article/123/majstrovstva-v-ladovom-hokeji
Spring's @PathVariable
would make it easy to handle this transparently.
Android: how to parse URL String with spaces to URI object?
You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes /
should be taken into account and which not. You cannot predict that on a raw String
beforehand. The problem really needs to be solved at a higher level. Where does that String
come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.
At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20
:
URI uri = new URI(string.replace(" ", "%20"));
Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri
utility class:
int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));
Do note that URLEncoder
is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded
rules (as used in HTML forms). See also Java URL encoding of query string parameters.
Parse a URI String into Name-Value Collection
If you are looking for a way to achieve it without using an external library, the following code will help you.
public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}
You can access the returned Map using <map>.get("client_id")
, with the URL given in your question this would return "SS".
UPDATE URL-Decoding added
UPDATE As this answer is still quite popular, I made an improved version of the method above, which handles multiple parameters with the same key and parameters with no value as well.
public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException {
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = url.getQuery().split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
query_pairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
query_pairs.get(key).add(value);
}
return query_pairs;
}
UPDATE Java8 version
public Map<String, List<String>> splitQuery(URL url) {
if (Strings.isNullOrEmpty(url.getQuery())) {
return Collections.emptyMap();
}
return Arrays.stream(url.getQuery().split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}
public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
final int idx = it.indexOf("=");
final String key = idx > 0 ? it.substring(0, idx) : it;
final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
return new SimpleImmutableEntry<>(
URLDecoder.decode(key, StandardCharsets.UTF_8),
URLDecoder.decode(value, StandardCharsets.UTF_8)
);
}
Running the above method with the URL
https://stackoverflow.com?param1=value1¶m2=¶m3=value3¶m3
returns this Map:
{param1=["value1"], param2=[null], param3=["value3", null]}
Turning a string into a Uri in Android
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
Related Topics
How to Solve the "Double-Checked Locking Is Broken" Declaration in Java
Encoding Url Query Parameters in Java
Variable Length (Dynamic) Arrays in Java
How to Make an Array of Arrays in Java
Turning Off Hibernate Logging Console Output
Sort Arrays of Primitive Types in Descending Order
Singleton Class with Several Different Classloaders
Can Not Find the Tag Library Descriptor for "Http://Java.Sun.Com/Jsp/Jstl/Core"
Using File.Listfiles with Filenameextensionfilter
Custom JSON Deserialization with Jackson
Background Timer Task in Jsp/Servlet Web Application
How to Use an Arraylist as a Prepared Statement Parameter