【问题标题】:How to get redirected URL on Android? [duplicate]如何在 Android 上获取重定向 URL? [复制]
【发布时间】:2015-05-27 12:19:16
【问题描述】:

我可以用这段代码在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中的错误日志

【问题讨论】:

  • 我认为您需要在清单文件中添加相应的权限。你添加网络权限了吗?

标签: java android http url redirect


【解决方案1】:

如您所见,最底部的例外是NetworkOnMainThreadException。为确保性能,Android SDK 会阻止开发人员(及其应用程序)在主 (UI) 线程上进行非本地连接及其操作。您可以使用您发布的相同代码 sn-p,您只需要确保它在非 UI 线程上运行。

例如

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

【讨论】:

  • 我爱声誉农民...这个问题应该标记为重复...
  • 如果我这样做,它会给我一些未处理的异常......
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 2013-02-24
  • 2011-03-22
  • 2018-05-02
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多