List of usage examples for java.net HttpURLConnection HTTP_MOVED_PERM
int HTTP_MOVED_PERM
To view the source code for java.net HttpURLConnection HTTP_MOVED_PERM.
Click Source Link
From source file:Main.java
public static void main(String[] argv) throws Exception { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection(); con.setRequestMethod("HEAD"); System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM); }
From source file:Main.java
private static String getRedrectUrl(String url) throws IOException { Response response = Jsoup.connect(url).followRedirects(false).execute(); int status = response.statusCode(); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { return response.header("location"); }/*from w ww .ja va 2s . c om*/ return null; }
From source file:Main.java
public static URI unredirect(URI uri) throws IOException { if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) { return uri; }//from ww w .j av a2s .c o m 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(); } }
From source file:Main.java
/** * On some devices we have to hack://from ww w . j av a2 s.c o m * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:com.shopgun.android.sdk.network.impl.DefaultRedirectProtocol.java
@Override public boolean isRedirectRequested(Request<?> request, HttpResponse response, ArrayList<URL> previouslyVisited) throws IOException { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { request.addEvent("request-redirected-statuscode-" + statusCode); return true; }/*from w w w. j a va 2 s. co m*/ return false; }
From source file:Main.java
/** * Return an {@link InputStream} from the given url or null if failed to retrieve the content * /*from w ww.ja va 2 s .c om*/ * @param uri * @return */ static InputStream openRemoteInputStream(Uri uri) { java.net.URL finalUrl; try { finalUrl = new java.net.URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); return null; } HttpURLConnection connection; try { connection = (HttpURLConnection) finalUrl.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } connection.setInstanceFollowRedirects(false); int code; try { code = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); return null; } // permanent redirection if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_SEE_OTHER) { String newLocation = connection.getHeaderField("Location"); return openRemoteInputStream(Uri.parse(newLocation)); } try { return (InputStream) finalUrl.getContent(); } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:uk.co.jassoft.network.Network.java
public InputStream read(String httpUrl, String method, boolean cache) throws IOException { HttpURLConnection conn = null; try {//w ww . java 2 s . c om URL base, next; String location; while (true) { // inputing the keywords to google search engine URL url = new URL(httpUrl); // if(cache) { // //Proxy instance, proxy ip = 10.0.0.1 with port 8080 // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128)); // // makking connection to the internet // conn = (HttpURLConnection) url.openConnection(proxy); // } // else { conn = (HttpURLConnection) url.openConnection(); // } conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); conn.setRequestMethod(method); conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)"); conn.setRequestProperty("Accept-Encoding", "gzip"); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: location = conn.getHeaderField("Location"); base = new URL(httpUrl); next = new URL(base, location); // Deal with relative URLs httpUrl = next.toExternalForm(); continue; } break; } if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) { throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]", conn.getContentType())); } if ("gzip".equals(conn.getContentEncoding())) { return new GZIPInputStream(conn.getInputStream()); } // getting the input stream of page html into bufferedreader return conn.getInputStream(); } catch (Exception exception) { throw new IOException(exception); } finally { if (conn != null && conn.getErrorStream() != null) { conn.getErrorStream().close(); } } }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/* ww w .ja v a 2 s.com*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:net.mceoin.cominghome.api.NestUtil.java
/** * Make HTTP/JSON call to Nest and set away status. * * @param access_token OAuth token to allow access to Nest * @param structure_id ID of structure with thermostat * @param away_status Either "home" or "away" * @return Equal to "Success" if successful, otherwise it contains a hint on the error. *//* w ww . j av a 2s. c o m*/ public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) { String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); String payload = "\"" + away_status + "\""; OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); log.info(payload); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); urlConnection.setRequestProperty("Accept", "application/json"); // System.out.println("Redirect to URL : " + newUrl); wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) { return "Error: " + errorResult; } else { return "Success"; } }
From source file:com.astamuse.asta4d.web.dispatch.RedirectUtil.java
public static void redirectToUrlWithSavedFlashScopeData(HttpServletResponse response, int status, String url) { // regulate status if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) { ///*ww w . j a v a2 s .c om*/ } else { status = HttpURLConnection.HTTP_MOVED_TEMP; } // check illegal url if (url.indexOf('\n') >= 0 || url.indexOf('\r') >= 0) { throw new RuntimeException("illegal redirct url:" + url); } // before redirect task Map<String, RedirectInterceptor> interceptorMap = Context.getCurrentThreadContext() .getData(RedirectInterceptorMapKey); if (interceptorMap != null) { for (RedirectInterceptor interceptor : interceptorMap.values()) { interceptor.beforeRedirect(); } addFlashScopeData(RedirectInterceptorMapKey, interceptorMap); } // create flash data map Map<String, Object> dataMap = new HashMap<String, Object>(); WebApplicationContext context = Context.getCurrentThreadContext(); List<Map<String, Object>> dataList = context.getData(FlashScopeDataListKey); if (dataList != null) { for (Map<String, Object> map : dataList) { dataMap.putAll(map); } } // save flash data map if (!dataMap.isEmpty()) { String flashScopeId = SecureIdGenerator.createEncryptedURLSafeId(); WebApplicationConfiguration.getWebApplicationConfiguration().getExpirableDataManager().put(flashScopeId, dataMap, DATA_EXPIRE_TIME_MILLI_SECONDS); // create target url if (url.contains("?")) { url = url + '&' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId; } else { url = url + '?' + KEY_FLASH_SCOPE_ID + '=' + flashScopeId; } } // do redirection response.setStatus(status); response.addHeader("Location", url); }