Get resulting URL in Java
Is it possible to get the resulting URL from a given URL? For example
System.out.println(realUrl("sourceforge.com"));
private String realUrl(String url)
{
....
}
Should print the re开发者_StackOverflowsulting URL "http://sourceforge.net/", and similarly tinyurls would return the destination URL
You can:
Check if a protocol is present in the string. If not, append
http://
Then use an HTTP client (like HttpClient) to open the URL. Then follow redirects (
.setFollowRedirects(true)
) until it stops redirecting. That would be the "final" or "real" URL.
Some example code for HttpClient can be found here:
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/
(See TrivialApp.java
to get started)
Not tested properly .
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;
}
}
精彩评论