90

I have to change URL to URI, please guide me how can I change it.

I have tried a lot, but not getting the solution. Any help is appreciated. I can also attach code snippet if required.

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
Programmer
  • 5,360
  • 10
  • 37
  • 61
  • see this link http://stackoverflow.com/questions/2593214/android-howto-parse-url-string-with-spaces-to-uri-object –  Mar 12 '12 at 07:04

4 Answers4

125

We can parse any URL using Uri.parse(String) method.

Code Snippet :

Uri uri =  Uri.parse( "http://www.stackoverflow.com" );
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
35
final String myUrlStr = "xyz";
URL url;
Uri uri;
try {
    url = new URL(myUrlStr);
    uri = Uri.parse( url.toURI().toString() );
} catch (MalformedURLException e1) {
    e1.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
JJD
  • 50,076
  • 60
  • 203
  • 339
Sparky
  • 8,437
  • 1
  • 29
  • 41
  • 1
    At first glance that answer looks convoluted. Why convert to string and then parse? The reason is that `toURI()` returns a `java.net.URI`. So we need to map to string and then parse into `android.net.Uri`. Good answer – tir38 Oct 31 '14 at 20:13
1

This is my 2 Cents , it could help someone else.

The standard URL Parsing might not be good idea if you have variables passed to the URL as Query

String your_url_which_is_not_going_to_change = "http://stackoverflow.com/?q="
String your_query_string = "some other stuff"
String query = null;

try {
  query = URLEncoder.encode(your_query_string, "utf-8");
} catch (UnsupportedEncodingException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

String url = your_url_which_is_not_going_to_change + query;

URL input = new URL(url);
etc... .

Hope it helps.

H.

Mr H
  • 5,254
  • 3
  • 38
  • 43
0

var url = "http://10.0.2.2:8080/(mymobileapp)/login.php";

var response = await http.post(Uri.parse(url), body: data);