Java tutorial
//package com.java2s; /* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; public class Main { private static final Collection<String> REDIRECTOR_DOMAINS = new HashSet<String>( Arrays.asList("amzn.to", "bit.ly", "bitly.com", "fb.me", "goo.gl", "is.gd", "j.mp", "lnkd.in", "ow.ly", "R.BEETAGG.COM", "r.beetagg.com", "SCN.BY", "su.pr", "t.co", "tinyurl.com", "tr.im")); public static URI unredirect(URI uri) throws IOException { if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) { return uri; } URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoInput(false); connection.setRequestMethod("HEAD"); connection.setRequestProperty("User-Agent", "ZXing (Android)"); try { connection.connect(); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_MULT_CHOICE: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case 307: // No constant for 307 Temporary Redirect ? String location = connection.getHeaderField("Location"); if (location != null) { try { return new URI(location); } catch (URISyntaxException e) { // nevermind } } } return uri; } finally { connection.disconnect(); } } }