I have the following code which expands the shortened url.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
public class ExpandUrl {
public static void main(String[] args) throws IOException {
String shortenedUrl = "2q3GMg0"; //read note at the bottom.
String expandedURL = ExpandUrl.expand(shortenedUrl);
System.out.println("expanded url is : " + expandedURL);
}
public static String expand(String shortenedUrl) throws IOException {
URL url = new URL(shortenedUrl);
// open connection
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("status is " + status);
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
}
The code expands some of the urls but returns null for some other urls.
e.g: it expands 2q3GMg0
but returns null when I use 9mglq8
although the status code is 200 for this. I have tested both url. Both are valid and has expanded form.
Note: Stackoverflow didn't allow me to put shortened link in body so I have just mentioned the hashcode.
Edit: Links for which I am getting null doesn't have a Location
header field. In such case how do I retrieve the original expanded link?
status is 200
Key: null value: [HTTP/1.1 200 OK]
Key: X-Cache value: [Hit from cloudfront]
Key: Server value: [Apache]
Key: Connection value: [keep-alive]
Key: Last-Modified value: [Sat, 12 May 2018 12:06:48 GMT]
Key: Date value: [Sat, 12 May 2018 12:11:30 GMT]
Key: Via value: [1.1 587a74dd892ff33ecf276aa569c8b68a.cloudfront.net (CloudFront)]
Key: X-Frame-Options value: [SAMEORIGIN]
Key: Accept-Ranges value: [bytes]
Key: Cache-Control value: [max-age=120, s-maxage=120, public]
Key: X-Amz-Cf-Id value: [-p1_VjHmvcGCI1PbQelSHpUectu_5NfCFUnPu_NUHCJ9_2lS2rTmlA==]
Key: Vary value: [Accept-Encoding]
Key: X-XSS-Protection value: [1]
Key: Content-Length value: [186539]
Key: Age value: [108]
Key: Content-Type value: [text/html]
Any kind of help will be greatly appreciated.
If the status code is 200
there is no redirection and there will be no Location
field in the header and hence null is returned when you try to access the value of Location
key. you can get the expanded URL using httpURLConnection.getURL()
.
If the status code is 301
or 302
there is a redirection and there will be a Location
field in the header. You can get the redirected URL as:
String expandedURL = httpURLConnection.getHeaderField("Location");
like you have done.
hope this helps.