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:com.github.hexocraftapi.updater.updater.Downloader.java
/** * Download the file and save it to the updater folder. *//* www. j a v a 2 s . c o m*/ private boolean downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { // Init connection HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl()); // always check HTTP response code first int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); connection = (HttpURLConnection) initConnection(new URL(newUrl)); responseCode = connection.getResponseCode(); } // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String fileURL = this.update.getDownloadUrl().toString(); String disposition = connection.getHeaderField("Content-Disposition"); String contentType = connection.getContentType(); int fileLength = connection.getContentLength(); // extracts file name from header field if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) fileName = disposition.substring(index + 10, disposition.length() - 1); } // extracts file name from URL else fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); // opens input stream from the HTTP connection in = new BufferedInputStream(connection.getInputStream()); // opens an output stream to save into file fout = new FileOutputStream(new File(this.updateFolder, fileName)); log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString()); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) fout.write(buffer, 0, bytesRead); log(Level.INFO, "File downloaded: " + fileName); } } catch (Exception ex) { log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful."); return false; } finally { try { if (in != null) in.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } try { if (fout != null) fout.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } return true; } }
From source file:mdretrieval.FileFetcher.java
public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException { String[] ret = new String[2]; HttpURLConnection urlConnection = null; InputStream inputStream = null; String dest = destinationURL; URL url = new URL(dest); Proxy proxy = null;//from www . j ava 2 s . co m if (ServerConstants.isProxyEnabled) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ServerConstants.hostname, ServerConstants.port)); urlConnection = (HttpURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpURLConnection) url.openConnection(); } boolean redirect = false; int status = urlConnection.getResponseCode(); if (Master.DEBUG_LEVEL >= Master.LOW) System.out.println("RESPONSE-CODE--> " + status); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newUrl = urlConnection.getHeaderField("Location"); dest = newUrl; urlConnection.disconnect(); if (Master.DEBUG_LEVEL > Master.LOW) System.out.println("REDIRECT--> " + newUrl); urlConnection = openMaybeProxyConnection(proxy, newUrl); } try { urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP); urlConnection.setDoInput(true); //urlConnection.setDoOutput(true); inputStream = urlConnection.getInputStream(); ret[1] = urlConnection.getHeaderField("Content-Type"); } catch (IllegalStateException e) { if (Master.DEBUG_LEVEL >= Master.LOW) System.out.println(" DEBUG: IllegalStateException"); urlConnection.disconnect(); HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest); conn2.setRequestMethod("GET"); conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP); conn2.setDoInput(true); inputStream = conn2.getInputStream(); ret[1] = conn2.getHeaderField("Content-Type"); } try { ret[0] = IOUtils.toString(inputStream); if (Master.DEBUG_LEVEL > Master.LOW) { System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type")); } } finally { IOUtils.closeQuietly(inputStream); urlConnection.disconnect(); } if (Master.DEBUG_LEVEL > Master.LOW) System.out.println("Done reading " + destinationURL); return ret; }
From source file:io.github.bonigarcia.wdm.Downloader.java
public static final synchronized void download(URL url, String version, String export, List<String> driverName) throws IOException { File targetFile = new File(getTarget(version, url)); File binary = null;//from w ww . ja va2s . c om // Check if binary exists boolean download = !targetFile.getParentFile().exists() || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0) || WdmConfig.getBoolean("wdm.override"); if (!download) { // Check if existing binary is valid Collection<File> listFiles = FileUtils.listFiles(targetFile.getParentFile(), null, true); for (File file : listFiles) { for (String s : driverName) { if (file.getName().startsWith(s) && file.canExecute()) { binary = file; log.debug("Using binary driver previously downloaded {}", binary); download = false; break; } else { download = true; } } if (!download) { break; } } } if (download) { log.info("Downloading {} to {}", url, targetFile); HttpURLConnection conn = getConnection(url); int responseCode = conn.getResponseCode(); log.debug("Response HTTP {}", responseCode); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { // HTTP Redirect URL newUrl = new URL(conn.getHeaderField("Location")); log.debug("Redirect to {}", newUrl); conn = getConnection(newUrl); } FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile); if (!export.contains("edge")) { binary = extract(targetFile, export); targetFile.delete(); } else { binary = targetFile; } } if (export != null) { BrowserManager.exportDriver(export, binary.toString()); } }
From source file:org.niord.proxy.rest.AbstractNiordService.java
/** * Creates a HTTP connection to the given URL and handles redirects. * @param url the URL//w w w . j av a 2 s.c o m * @return a HTTP connection to the given URL and handles redirects. */ HttpURLConnection createHttpUrlConnection(String url) throws IOException { HttpURLConnection con = newHttpUrlConnection(url); int status = con.getResponseCode(); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { // get redirect url from "location" header field String redirectUrl = con.getHeaderField("Location"); // open the new connection again con = newHttpUrlConnection(redirectUrl); } return con; }
From source file:org.jenkinsci.plugins.mber.FileDownloadCallable.java
public static String followRedirects(final String url) throws IOException { // Turn off auto redirect follow so we can read the final URL ourselves. // The internal parsing doesn't work with some of the headers used by Amazon. final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setUseCaches(false);//from ww w . j a va2 s .c o m connection.setInstanceFollowRedirects(false); connection.connect(); // Pull the redirect URL out of the "Location" header. Follow it recursively since it might be chained. if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) { final String redirectURL = connection.getHeaderField("Location"); return followRedirects(redirectURL); } return url; }
From source file:com.alexoree.jenkins.Main.java
private static String download(String localName, String remoteUrl) throws Exception { URL obj = new URL(remoteUrl); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000);// ww w. j a v a2s .co m System.out.println("Request URL ... " + remoteUrl); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1, newUrl.lastIndexOf("/")); String pluginname = localName.substring(localName.lastIndexOf("/") + 1); String ext = ""; if (pluginname.endsWith(".war")) ext = ".war"; else ext = ".hpi"; pluginname = pluginname.replace(ext, ""); localName = localName.replace(pluginname + ext, "/download/plugins/" + pluginname + "/" + version + "/"); new File(localName).mkdirs(); localName += pluginname + ext; System.out.println("Redirect to URL : " + newUrl); } if (new File(localName).exists()) { System.out.println(localName + " exists, skipping"); return localName; } byte[] buffer = new byte[2048]; FileOutputStream baos = new FileOutputStream(localName); InputStream inputStream = conn.getInputStream(); int totalBytes = 0; int read = inputStream.read(buffer); while (read > 0) { totalBytes += read; baos.write(buffer, 0, read); read = inputStream.read(buffer); } System.out.println("Retrieved " + totalBytes + "bytes"); return localName; }
From source file:com.none.tom.simplerssreader.net.FeedDownloader.java
@SuppressWarnings("ConstantConditions") public static InputStream getInputStream(final Context context, final String feedUrl) { final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class); final NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK); LogUtils.logError("No network connection"); return null; }//from w w w . j ava 2 s .co m URL url; try { url = new URL(feedUrl); } catch (final MalformedURLException e) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e); return null; } final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context); final boolean useHttpTorProxy = networkPrefs[0]; final boolean httpsOnly = networkPrefs[1]; final boolean followRedir = networkPrefs[2]; for (int nrRedirects = 0;; nrRedirects++) { if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS); LogUtils.logError("Too many redirects"); return null; } HttpURLConnection conn = null; try { if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY); LogUtils.logError("Attempting insecure connection"); return null; } if (useHttpTorProxy) { conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT))); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.connect(); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: return getInputStream(conn.getInputStream()); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: if (followRedir) { final String location = conn.getHeaderField("Location"); url = new URL(url, location); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) { SharedPrefUtils.updateSubscriptionUrl(context, url.toString()); } continue; } ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED); LogUtils.logError("Couldn't follow redirect"); return null; default: if (responseCode < 0) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE); LogUtils.logError("No valid HTTP response"); return null; } else if (responseCode >= 400 && responseCode <= 500) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT); } else if (responseCode >= 500 && responseCode <= 600) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED); } LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage()); return null; } } catch (final IOException e) { if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable")) || e instanceof SocketTimeoutException || e instanceof UnknownHostException) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e); } return null; } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:com.aitangba.volley.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); try {/*from w w w . java 2s. c om*/ // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); int statusCode = httpResponse.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) { Cache.Entry entry = request.getCacheEntry(); if (entry == null) { return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // A HTTP 304 response does not have all header fields. We // have to use the header fields from the cache entry plus // the new ones from the response. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 entry.responseHeaders.putAll(responseHeaders); return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // Handle moved resources if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { String newUrl = responseHeaders.get("Location"); request.setRedirectUrl(newUrl); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, httpResponse.getStatusCode()); if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusCode(); } else { throw new NoConnectionError(e); } if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl()); } else { VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); } if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED || statusCode == HttpURLConnection.HTTP_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { attemptRetryOnException("redirect", request, new RedirectError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(e); } } } }
From source file:com.andrious.btc.data.jsonUtils.java
private static boolean handleResponse(int response, HttpURLConnection conn) { if (response == HttpURLConnection.HTTP_OK) { return true; }/*from w w w . j a v a 2s. c o m*/ if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_SEE_OTHER) { String newURL = conn.getHeaderField("Location"); conn.disconnect(); try { // get redirect url from "location" header field and open a new connection again conn = urlConnect(newURL); return true; } catch (IOException ex) { throw new RuntimeException(ex); } } // Nothing to be done. Can't go any further. return false; }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
/** * Implement a simple proxy/* w w w. jav a 2 s. c o m*/ * * @param requestedURL the requested URL * @param req the HttpServletRequest * @return */ @GET @Path("proxy") public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL, @Context HttpServletRequest req) { BufferedReader in = null; try { URL url = new URL(requestedURL); URLConnection urlConnection = url.openConnection(); int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout(); // Set base properties urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT); if (StringUtils.isNotBlank(acceptedDataFormat)) { urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat); } // Open the connection urlConnection.connect(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; int statusCode = httpConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { // Follow the redirect String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION); httpConnection.disconnect(); if (StringUtils.isNotBlank(newLocation)) { return this.proxy(newLocation, req); } else { return Response.status(statusCode).build(); } } else if (statusCode == HttpURLConnection.HTTP_OK) { // Send the response StringBuilder sbf = new StringBuilder(); // Check if the contentType is supported boolean contentTypeSupported = false; String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE); List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes(); if (contentType != null) { for (String cMime : supportedMimeTypes) { if (contentType.equals(cMime) || contentType.contains(cMime)) { contentTypeSupported = true; break; } } } if (!contentTypeSupported) { httpConnection.disconnect(); return Response.status(Status.NOT_ACCEPTABLE).build(); } String contentEncoding = httpConnection.getContentEncoding(); if (StringUtils.isBlank(contentEncoding)) { contentEncoding = "UTF-8"; } InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(), Charset.forName(contentEncoding)); in = new BufferedReader(inStrem); String inputLine; while ((inputLine = in.readLine()) != null) { sbf.append(inputLine); sbf.append("\r\n"); } in.close(); httpConnection.disconnect(); return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType) .entity(sbf.toString()).build(); } else { httpConnection.disconnect(); return Response.status(statusCode).build(); } } return Response.status(Status.BAD_REQUEST).build(); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.BAD_REQUEST).build(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } } }