如何在Android上获取重定向的URL?

时间:2015-03-24 08:56:09

标签: java android http url redirect

我可以使用以下代码在java中执行此操作:

  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();

现在在Android中,当点击一个按钮时,它会调用:

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();
}

这是我在android中的错误日志 enter image description here

1 个答案:

答案 0 :(得分:1)

就像你看到最底层的例外是NetworkOnMainThreadException。为了确保性能,Android SDK可以防止开发人员(及其应用程序)在主(UI)线程上进行非本地连接及其操作。您可以使用您发布的相同代码段,只需要确保它在非UI线程上运行。

E.g。

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

或者如果您希望它在点击时执行:

 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();
}