Example usage for java.net HttpURLConnection getExpiration

List of usage examples for java.net HttpURLConnection getExpiration

Introduction

In this page you can find the example usage for java.net HttpURLConnection getExpiration.

Prototype

public long getExpiration() 

Source Link

Document

Returns the value of the expires header field.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    long date = httpCon.getExpiration();
    if (date == 0)
        System.out.println("No expiration information.");
    else/*from   ww  w .ja va 2  s  .  co  m*/
        System.out.println("Expires: " + new Date(date));

}

From source file:net.dontdrinkandroot.lastfm.api.ws.fetcher.DiskBufferedFetcher.java

protected LastfmResponse fetchResponse(final HttpURLConnection conn, final File targetFile)
        throws LastfmWebServicesException {

    /* Open input stream */
    InputStream is = null;//from   www  . jav a  2s .com

    try {
        is = conn.getInputStream();
    } catch (final IOException e) {
        is = conn.getErrorStream();
    }

    if (is == null) {
        conn.disconnect();
        throw new LastfmWebServicesException(LastfmWebServicesException.STREAM_WAS_NULL, "Stream was null");
    }

    if (targetFile != null) {
        this.logger.info("Writing response to {}", targetFile);
        try {
            FileUtils.copyInputStreamToFile(is, targetFile);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

    try {
        is = new FileInputStream(targetFile);
    } catch (final FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    /* Read document from inputstream */
    final Document doc = this.parseDoc(is);

    /* Close connection */
    try {
        is.close();
        conn.disconnect();
    } catch (final IOException e) {
        this.logger.error("Closing Http connection failed", e);
    }

    final long expiration = conn.getExpiration();
    final LastfmResponse response = new LastfmResponse(doc, expiration);

    return response;
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Rcupere la resource via un HttpConnection
 *
 * @param resource/*from   w  w w.  j  a va  2s  .c o  m*/
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
protected HttpURLConnection getConnectionForResource(String resource)
        throws MalformedURLException, IOException {
    StringBuilder sb = new StringBuilder("http://localhost:");
    sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append(resource);
    URL url = new URL(sb.toString());
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    //      Authenticator.setDefault(new Authenticator() {
    //         @Override
    //         protected PasswordAuthentication getPasswordAuthentication() {
    //            return new PasswordAuthentication("demo", "demo".toCharArray());
    //         }
    //      });
    //    ou
    //      String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary("demo:demo".getBytes());
    //      System.out.println(basicAuth);
    //      uc.setRequestProperty("Authorization", basicAuth);
    System.out.println("Content-type: " + uc.getContentType());
    System.out.println("Date: " + new Date(uc.getDate()));
    System.out.println("Last modified: " + new Date(uc.getLastModified()));
    System.out.println("Expiration date: " + new Date(uc.getExpiration()));
    System.out.println("Response code: " + uc.getResponseCode());
    assertThat(uc.getResponseCode()).isEqualTo(200).as("'%s' is unreachable", sb);
    return uc;
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag)
        throws CommunicationException {

    /* locals ---------------------------------- */
    Result result = new Result();
    int code = 0;
    HttpURLConnection conn;
    /* locals ---------------------------------- */

    try {//www  . jav a2 s .  c o m
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        sendCookies(session, url, conn);
        if (etag != null) {
            conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$
        }

        String strUrl = url.toExternalForm();
        if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) {
            conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$
        }

        if (modifiedSince > 0) {
            // see sun bugid: 4397096
            // if HTTP_Util library is used, the original method may also be used.
            // conn.setIfModifiedSince(modifiedSince);
            conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince));
        }
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);

    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$
        throw new ConnectException("error loading '" + url.toString() + "' form server:", exc);
    }

    try {
        code = conn.getResponseCode();
        if (code == HttpURLConnection.HTTP_NOT_MODIFIED) {
            result.contentLength_ = 0;
            result.lastModified_ = conn.getLastModified();
            if (result.lastModified_ <= 0) {
                result.lastModified_ = modifiedSince;
            }
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            if (result.etag_ == null) {
                result.etag_ = etag;
            }
            log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_OK) {
            result.contentLength_ = conn.getContentLength();
            result.lastModified_ = conn.getLastModified();
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER);

            result.setBuffer(this.readOutput(conn));

            if (result.contentLength_ < 0) {
                result.contentLength_ = result.buffer_.length;
            }
        } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        } else {
            if (code < 500)
                throw new ConnectException("error loading '" + url.toString() + "' from the server:", code);
            else
                throw new ServerException("error loading '" + url.toString() + "' from the server:", code);
        }
        readCookies(session, url, conn);
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex);
        else
            throw new ServerException("error loading '" + url.toString() + "' from the server:", ex);
    }

    return result;
}

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request//from  w  w w  . j  a v  a2  s  .  c o  m
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // An OCSP request, ocspTestCert is already created in earlier tests
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*w ww .ja v a 2 s . c o  m*/
    String reqString = new String(Base64.encode(req.getEncoded(), false));
    URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8"));
    log.debug("OCSP Request: " + url.toExternalForm());
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    assertEquals(
            "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)",
            200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    // Just output the headers to stdout so we can visually inspect them if
    // something goes wrong
    Set<String> keys = con.getHeaderFields().keySet();
    for (String field : keys) {
        List<String> values = con.getHeaderFields().get(field);
        for (String value : values) {
            log.info(field + ": " + value);
        }
    }
    String eTag = con.getHeaderField("ETag");
    assertNotNull(
            "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            eTag);
    assertTrue("ETag is messed up.",
            ("\"" + new String(
                    Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"")
                            .equals(eTag));
    long date = con.getHeaderFieldDate("Date", -1);
    assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1);
    long lastModified = con.getHeaderFieldDate("Last-Modified", -1);
    assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1);
    // assertTrue("Last-Modified is after response was sent",
    // lastModified<=date); This will not hold on JBoss AS due to the
    // caching of the Date-header
    long expires = con.getExpiration();
    assertTrue("Expires is before response was sent", expires >= date);
    assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0);
    String cacheControl = con.getHeaderField("Cache-Control");
    assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl);
    assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("public"));
    assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("no-transform"));
    assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("must-revalidate"));
    Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl);
    assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches());
    int maxAge = Integer.parseInt(matcher.group(1));
    log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000));
    assertTrue(
            "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            expires != lastModified);
    assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.",
            maxAge < (expires - lastModified) / 1000);
    // assertTrue("Response cannot be produced after it was sent.",
    // brep.getProducedAt().getTime() <= date); This might not hold on JBoss
    // AS due to the caching of the Date-header
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
    SingleResp[] singleResps = brep.getResponses();
    assertNotNull("SingleResps should not be null.", singleResps);
    assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1);
    assertEquals("Serno in response does not match serno in request.",
            singleResps[0].getCertID().getSerialNumber(), serialNumber);
    assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null);
    assertTrue(
            "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'",
            singleResps[0].getThisUpdate().getTime() == lastModified);
    assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'",
            singleResps[0].getNextUpdate().getTime() == expires);
    assertTrue("Response cannot be produced before it was last modified..",
            brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime());
}