List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.dcm4che3.tool.wadouri.WadoURI.java
private static String sendRequest(final WadoURI main) throws Exception { URL newUrl = new URL(setWadoRequestQueryParams(main, main.getUrl())); System.out.println(newUrl.toString()); HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setDoOutput(true);//from ww w. ja v a 2s.co m connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("GET"); if (main.getRequestTimeOut() != null) { connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut())); connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut())); } connection.setUseCaches(false); String response = "Server responded with " + connection.getResponseCode() + " - " + connection.getResponseMessage(); InputStream in = connection.getInputStream(); String contentType = connection.getHeaderField("Content-Type"); if (contentType.contains("application")) { if (contentType.contains("application/dicom+xml")) writeXML(in, main); else if (contentType.contains("application/pdf")) writeFile(in, main, ".pdf"); else //dicom writeFile(in, main, ".dcm"); } else if (contentType.contains("image")) { if (contentType.contains("image/jpeg")) writeFile(in, main, ".jpeg"); else if (contentType.contains("image/png")) writeFile(in, main, ".png"); else //gif writeFile(in, main, ".gif"); } else if (contentType.contains("text")) { if (contentType.contains("text/html")) { writeFile(in, main, ".html"); } else if (contentType.contains("text/rtf")) { writeFile(in, main, ".rtf"); } else // text/plain writeFile(in, main, ".txt"); } connection.disconnect(); return response; }
From source file:com.jwrapper.maven.java.JavaDownloadMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {/* ww w . j a v a2 s. co m*/ setupNonVerifingSSL(); final String javaRemoteURL = javaRemoteURL(); final String javaLocalURL = javaLocalURL(); logger().info("javaRemoteURL: {}", javaRemoteURL); logger().info("javaLocalURL : {}", javaLocalURL); final File file = new File(javaLocalURL()); if (!javaEveryTime() && file.exists()) { logger().info("Java artifact is present, skip download."); return; } else { logger().info("Java artifact is missing, make download."); } file.getParentFile().mkdirs(); /** Oracle likes redirects. */ HttpURLConnection connection = connection(javaRemoteURL()); while (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) { connection = connection(connection.getHeaderField("Location")); logger().info("redirect: {}", connection); } final ProgressInputStream input = new ProgressInputStream(connection.getInputStream(), connection.getContentLengthLong()); final PropertyChangeListener listener = new PropertyChangeListener() { long current = System.currentTimeMillis(); @Override public void propertyChange(final PropertyChangeEvent event) { if (System.currentTimeMillis() - current > 1000) { current = System.currentTimeMillis(); logger().info("progress: {}", event.getNewValue()); } } }; input.addPropertyChangeListener(listener); final OutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); if (file.length() < 1000 * 1000) { throw new IllegalStateException("Download failure."); } logger().info("Java artifact downloaded: {} bytes.", file.length()); } catch (final Throwable e) { logger().error("", e); throw new MojoExecutionException("", e); } }
From source file:com.playhaven.android.req.UrlRequest.java
@Override public String call() throws MalformedURLException, IOException, PlayHavenException { HttpURLConnection connection = (HttpURLConnection) new URL(mInitialUrl).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty(CoreProtocolPNames.USER_AGENT, UserAgent.USER_AGENT); connection.getContent(); // .getHeaderFields() will return null if headers not accessed once before if (connection.getHeaderFields().containsKey(LOCATION_HEADER)) { return connection.getHeaderField(LOCATION_HEADER); } else {/*from ww w . ja v a2 s. c om*/ throw new PlayHavenException(); } }
From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java
/** * Retrieves {@link InputStream} of image by URI (image is located in the network). * * @param imageUri Image URI/*from w w w . j a v a 2s . c o m*/ * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { HttpURLConnection conn = createConnection(imageUri, extra); int redirectCount = 0; while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { conn = createConnection(conn.getHeaderField("Location"), extra); redirectCount++; } InputStream imageStream; try { imageStream = conn.getInputStream(); } catch (IOException e) { // Read all data to allow reuse connection (http://bit.ly/1ad35PY) IoUtils.readAndCloseStream(conn.getErrorStream()); throw e; } return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength()); }
From source file:com.nexmo.sdk.core.client.Client.java
/** * Executes a connection, and validates that the body was supplied. * * @param connection A prepared HttpUrlConnection. * * @return The response object.// ww w . j av a 2 s.com * @throws IOException If an error occurs while connecting to the resource. * @throws InternalNetworkException If an internal sdk error occurs while parsing the response. */ @Override public Response execute(HttpURLConnection connection) throws IOException, InternalNetworkException { try { connection.connect(); if (connection.getResponseCode() == HttpStatus.SC_OK) { if (BuildConfig.DEBUG) Log.d(TAG, connection.getURL().toString()); String signatureSupplied = connection.getHeaderField(BaseService.RESPONSE_SIG); Response response = new Response(getResponseString(connection.getInputStream()), signatureSupplied); if (TextUtils.isEmpty(response.getBody())) throw new InternalNetworkException(TAG + "Internal error. Body response missing."); else return response; } else throw new InternalNetworkException( TAG + " Internal error. Unable to connect to server. " + connection.getResponseCode()); } finally { connection.disconnect(); } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {/*ww w . j a va 2 s .com*/ connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:org.niord.proxy.rest.AbstractNiordService.java
/** * Creates a HTTP connection to the given URL and handles redirects. * @param url the URL/* ww w .j a v a 2 s . c om*/ * @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.openmrs.module.ModuleUtil.java
/** * Convenience method to follow http to https redirects. Will follow a total of 5 redirects, * then fail out due to foolishness on the url's part. * * @param c the {@link URLConnection} to open * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403 * redirect.//from ww w .j av a 2 s . c om * @throws IOException * @see #getURLStream(URL) */ protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException { boolean redir; int redirects = 0; InputStream in = null; do { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).setInstanceFollowRedirects(false); } // We want to open the input stream before getting headers // because getHeaderField() et al swallow IOExceptions. in = c.getInputStream(); redir = false; if (c instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) c; int stat = http.getResponseCode(); if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) { URL base = http.getURL(); String loc = http.getHeaderField("Location"); URL target = null; if (loc != null) { target = new URL(base, loc); } http.disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol())) || redirects >= 5) { throw new SecurityException("illegal URL redirect"); } redir = true; c = target.openConnection(); redirects++; } } } while (redir); return in; }
From source file:com.mercandalli.android.apps.files.common.net.TaskGetDownload.java
public void fileFromUrlAuthorization(String url) { try {/*ww w. ja va 2s .c om*/ HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken()); conn.setRequestMethod("GET"); InputStream inputStream = conn.getInputStream(); long lengthOfFile = Long.parseLong(conn.getHeaderField("Content-Length")); OutputStream outputStream = new FileOutputStream(mUrlOuput); byte data[] = new byte[1024]; long total = 0; int missed_value = 50; int missed_counter = 0; int count; while ((count = inputStream.read(data)) != -1) { total += count; missed_counter++; if (missed_counter > missed_value) { // publishing the progress.... // After this onProgressUpdate will be called publishProgress(((total * 100) / lengthOfFile), total); missed_counter = 0; } // writing data to file outputStream.write(data, 0, count); } // flushing output outputStream.flush(); // closing streams outputStream.close(); inputStream.close(); conn.disconnect(); } catch (IOException e) { Log.e(getClass().getName(), "IOException: Download exception.", e); } }
From source file:org.smartfrog.services.www.bulkio.client.SunJavaBulkIOClient.java
@Override public long doDownload(long ioSize) throws IOException, InterruptedException { validateURL();//from ww w . j a v a 2 s.co m URL target = createFullURL(ioSize, format); getLog().info("Downloading " + ioSize + " bytes from " + target); CRC32 checksum = new CRC32(); HttpURLConnection connection = openConnection(target); connection.setRequestMethod(HttpAttributes.METHOD_GET); connection.setDoOutput(false); connection.connect(); checkStatusCode(target, connection, HttpURLConnection.HTTP_OK); String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH); long contentLength = Long.parseLong(contentLengthHeader); if (contentLength != ioSize) { throw new IOException("Wrong content length returned from " + target + " - expected " + ioSize + " but got " + contentLength); } String formatHeader = connection.getHeaderField(HttpHeaders.CONTENT_TYPE); if (!format.equals(formatHeader)) { throw new IOException("Wrong content type returned from " + target + " - expected " + format + " but got " + formatHeader); } InputStream stream = connection.getInputStream(); long bytes = 0; try { for (bytes = 0; bytes < ioSize; bytes++) { int octet = stream.read(); checksum.update(octet); if (interrupted) { throw new InterruptedException( "Interrupted after reading" + bytes + " bytes" + " from " + target); } } } finally { closeQuietly(stream); } long actualChecksum = checksum.getValue(); getLog().info("Download finished after " + bytes + " bytes, checksum=" + actualChecksum); if (bytes != ioSize) { throw new IOException("Wrong content length downloaded from " + target + " - requested " + ioSize + " but got " + bytes); } if (expectedChecksumFromGet >= 0 && expectedChecksumFromGet != actualChecksum) { throw new IOException("Wrong checksum from download of " + ioSize + " bytes " + " from " + target + " expected " + expectedChecksumFromGet + " but got " + actualChecksum); } return bytes; }