-1

I can do it in java with this code:

  String url = "http://t.co/i5dE1K4vSs";

  URLConnection conn = new URL( url ).openConnection();
  System.out.println( "orignal url: " + conn.getURL() );
  conn.connect();
  System.out.println( "connected url: " + conn.getURL() );
  InputStream inputS = conn.getInputStream();
  System.out.println( "redirected url: " + conn.getURL() );
  inputS.close();

Now in android when a button is clicked it calls :

public void followRedirects(View v) throws ClientProtocolException, IOException, URISyntaxException
{
  String url = "http://t.co/i5dE1K4vSs";

  URLConnection conn = new URL( url ).openConnection();
  System.out.println( "orignal url: " + conn.getURL() );
  conn.connect();
  System.out.println( "connected url: " + conn.getURL() );
  InputStream inputS = conn.getInputStream();
  System.out.println( "redirected url: " + conn.getURL() );
  inputS.close();
}

This is my error log in android enter image description here

pepuch
  • 6,346
  • 7
  • 51
  • 84
blaswtf
  • 91
  • 1
  • 6

1 Answers1

1

Like you see the bottom-most exception is NetworkOnMainThreadException. To ensure performance, Android SDK prevents developers (and their applications) to make non-local connections and their operations on the main (UI) thread. You can use the same code snippet you posted, you only need to make sure it's running on a non-UI thread.

E.g.

new Thread(new Runnable() {
    @Override
    public void run() {
        followRedirects(null);
    }
}).start();

Or if you want it to be executed on click:

 public void followRedirects(View v) throws ClientProtocolException, IOException, URISyntaxException
{
  new Thread(new Runnable() {
    @Override
    public void run() {
        String url = "http://t.co/i5dE1K4vSs";

        URLConnection conn = new URL( url ).openConnection();
        System.out.println( "orignal url: " + conn.getURL() );
        conn.connect();
        System.out.println( "connected url: " + conn.getURL() );
        InputStream inputS = conn.getInputStream();
        System.out.println( "redirected url: " + conn.getURL() );
        inputS.close();
    }
  }).start();
}
nstosic
  • 2,584
  • 1
  • 17
  • 21