Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取Java中的结果URL_Java_Url - Fatal编程技术网

获取Java中的结果URL

获取Java中的结果URL,java,url,Java,Url,是否可以从给定的URL获取结果URL?比如说 System.out.println(realUrl("sourceforge.com")); private String realUrl(String url) { .... } 应打印结果URL“”,类似地,TinyURL将返回目标URL您可以: 检查字符串中是否存在协议。如果没有,请附加http:// 然后使用HTTP客户端(如)打开URL。然后按照重定向(.setFollowRedirects(true))操作,直到它停止重定向。

是否可以从给定的URL获取结果URL?比如说

System.out.println(realUrl("sourceforge.com"));

private String  realUrl(String url)
{
 ....
}
应打印结果URL“”,类似地,TinyURL将返回目标URL

您可以:

  • 检查字符串中是否存在协议。如果没有,请附加
    http://

  • 然后使用HTTP客户端(如)打开URL。然后按照重定向(
    .setFollowRedirects(true)
    )操作,直到它停止重定向。这将是“最终”或“真实”的URL

可以在此处找到HttpClient的一些示例代码:


(请参见
app.java
开始)

未正确测试

import java.io.*;
import java.net.*;

public class UrlCon3
  {

    public static void main(String[] args)
      {
        String x="http://tinyurl.com/cys7t";
        while(x!=null)
        {
            System.out.println(x);
            x=getRedirectionUrl(x);
        }

      }

    static String getRedirectionUrl(String x)
    {
        BufferedReader in = null;
        try
          {
            URL url = new URL(x);
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection uc = (HttpURLConnection)url.openConnection();
            uc.connect();
            in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            return(uc.getHeaderField("Location"));
          }
        catch (MalformedURLException e)
          {
            e.printStackTrace();
          }
        catch (IOException e)
          {
            e.printStackTrace();
          }
        finally
          {
            try
              {
                if (null != in)
                  {
                    in.close();
                  }
              }
            catch (IOException e)
              {
                // ignore
              }
          }
        return null;
    }
  }

很抱歉,我误解了你的问题,因为我得到了URL的“内容”。请删除我的答案