Example usage for java.net URLConnection getHeaderField

List of usage examples for java.net URLConnection getHeaderField

Introduction

In this page you can find the example usage for java.net URLConnection getHeaderField.

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:ddf.catalog.resource.impl.URLResourceReader.java

private ResourceResponse retrieveFileProduct(URI resourceURI, String productName, String bytesToSkip)
        throws ResourceNotFoundException {
    URLConnection connection = null;
    try {//from w w  w. j ava2 s.  c  om
        LOGGER.debug("Opening connection to: {}", resourceURI.toString());
        connection = resourceURI.toURL().openConnection();

        productName = StringUtils.defaultIfBlank(
                handleContentDispositionHeader(connection.getHeaderField(HttpHeaders.CONTENT_DISPOSITION)),
                productName);

        String mimeType = getMimeType(resourceURI, productName);

        InputStream is = connection.getInputStream();

        skipBytes(is, bytesToSkip);

        return new ResourceResponseImpl(
                new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName)));
    } catch (MimeTypeResolutionException | IOException e) {
        LOGGER.error("Error retrieving resource", e);
        throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e);
    }
}

From source file:com.spinn3r.api.BaseClient.java

private void setMoreResults(URLConnection conn, PartialBaseClientResult<ResultType> result) {

    String more = conn.getHeaderField(X_MORE_RESULTS);

    if (more == null)
        result.setHasMoreResultsHeader(false);

    else {//from  www. j  a v a  2  s. com
        result.setHasMoreResultsHeader(true);

        if ("true".equals(more))
            result.setHasMoreResults(true);
        else
            result.setHasMoreResults(false);
    }
}

From source file:util.io.IOUtilities.java

/**
 * Originally copied from javax.swing.JEditorPane.
 * <p>/* w w w. j  av a  2s . c o  m*/
 * Fetches a stream for the given URL, which is about to
 * be loaded by the <code>setPage</code> method.  By
 * default, this simply opens the URL and returns the
 * stream.  This can be reimplemented to do useful things
 * like fetch the stream from a cache, monitor the progress
 * of the stream, etc.
 * <p>
 * This method is expected to have the the side effect of
 * establishing the content type, and therefore setting the
 * appropriate <code>EditorKit</code> to use for loading the stream.
 * <p>
 * If this the stream was an http connection, redirects
 * will be followed and the resulting URL will be set as
 * the <code>Document.StreamDescriptionProperty</code> so that relative
 * URL's can be properly resolved.
 *
 * @param page the URL of the page
 * @param followRedirects Follow redirects.
 * @param timeout The read timeout.
 * @param userName The user name to use for the connection.
 * @param userPassword The password to use for the connection.
 * @throws IOException if something went wrong.
 * @return a stream reading data from the specified URL.
 */
public static InputStream getStream(URL page, boolean followRedirects, int timeout, String userName,
        String userPassword) throws IOException {
    URLConnection conn = page.openConnection();

    if (userName != null && userPassword != null) {
        String password = userName + ":" + userPassword;
        String encodedPassword = new String(Base64.encodeBase64(password.getBytes()));
        conn.setRequestProperty("Authorization", "Basic " + encodedPassword);
    }

    if (timeout > 0) {
        conn.setReadTimeout(timeout);
    }

    if (followRedirects && (conn instanceof HttpURLConnection)) {
        HttpURLConnection hconn = (HttpURLConnection) conn;
        hconn.setInstanceFollowRedirects(false);

        int response = hconn.getResponseCode();
        boolean redirect = (response >= 300 && response <= 399);

        // In the case of a redirect, we want to actually change the URL
        // that was input to the new, redirected URL
        if (redirect) {
            String loc = conn.getHeaderField("Location");
            if (loc == null) {
                throw new FileNotFoundException(
                        "URL points to a redirect without " + "target location: " + page);
            }
            if (loc.startsWith("http")) {
                page = new URL(loc);
            } else {
                page = new URL(page, loc);
            }
            return getStream(page, followRedirects, timeout, userName, userPassword);
        }
    }

    InputStream in = conn.getInputStream();
    return in;
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * @throws Exception/*from   www  . j  av  a  2  s. c  o m*/
 */
@Test
public void testResponseHeader() throws Exception {
    final String headerValue = "bla blah";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testResponseHeader");
            response.setHeader(HeaderName.COOKIE, headerValue);
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.connect();
        assertEquals(headerValue, connection.getHeaderField("Cookie"));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * @throws Exception//from www. j ava  2s.  c  o m
 */
@Test
public void testScheme() throws Exception {
    final URIScheme[] schemes = new URIScheme[1];
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling scheme-test");
            schemes[0] = request.getScheme();
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.connect();
        //this is for the connection to get real
        connection.getHeaderField("Cookie");
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
    assertEquals(URIScheme.HTTP, schemes[0]);
}

From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java

/**
 * Send activation request if subscribed to the activated URI
 *
 * @param subscriber//  w  ww  .j  av a2s. c  om
 * @param activationContent
 * @throws ExchangeException
 */
private synchronized void activate(Subscriber subscriber, ActivationContent activationContent)
        throws ExchangeException {
    if (!isSubscribed(subscriber)) {
        if (log.isDebugEnabled()) {
            log.debug("Exchange : subscriber [{}] is not subscribed to {}", subscriber.getName(), this.path);
        }
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug("Exchange : sending activation request to {}", subscriber.getName()); //$NON-NLS-1$
        log.debug("Exchange : user [{}]", this.user.getName()); //$NON-NLS-1$
    }
    String handle = getActivationURL(subscriber);
    try {
        URL url = new URL(handle);
        URLConnection urlConnection = url.openConnection();
        this.addActivationHeaders(urlConnection, activationContent);

        Transporter.transport(urlConnection, activationContent);

        String status = urlConnection.getHeaderField(SimpleSyndicator.ACTIVATION_ATTRIBUTE_STATUS);

        // check if the activation failed
        if (StringUtils.equals(status, SimpleSyndicator.ACTIVATION_FAILED)) {
            String message = urlConnection.getHeaderField(SimpleSyndicator.ACTIVATION_ATTRIBUTE_MESSAGE);
            throw new ExchangeException("Message received from subscriber: " + message);
        }
        urlConnection.getContent();
        log.info("Exchange : activation request received by {}", subscriber.getName()); //$NON-NLS-1$
    } catch (ExchangeException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw new ExchangeException("Incorrect URL for subscriber " + subscriber + "[" + handle + "]");
    } catch (IOException e) {
        throw new ExchangeException(
                "Not able to send the activation request [" + handle + "]: " + e.getMessage());
    } catch (Exception e) {
        throw new ExchangeException(e);
    }
}

From source file:org.clapper.curn.FeedDownloadThread.java

/**
 * Get the input stream for a URL. Handles compressed data.
 *
 * @param conn the <tt>URLConnection</tt> to process
 *
 * @return the <tt>InputStream</tt>
 *
 * @throws IOException I/O error// w  ww  . ja v a2s . c  o m
 */
private InputStream getURLInputStream(final URLConnection conn) throws IOException {
    InputStream is = conn.getInputStream();
    String ce = conn.getHeaderField("content-encoding");

    if (ce != null) {
        String urlString = conn.getURL().toString();

        log.debug("URL \"" + urlString + "\" -> Content-Encoding: " + ce);
        if (ce.indexOf("gzip") != -1) {
            log.debug("URL \"" + urlString + "\" is compressed. Using GZIPInputStream.");
            is = new GZIPInputStream(is);
        }
    }

    return is;
}

From source file:BihuHttpUtil.java

/**
 * ? URL ??POST//  ww  w .  j  a va2s .com
 *
 * @param url
 *               ?? URL
 * @param param
 *               ?? name1=value1&name2=value2 ?
 * @param sessionId
 *             ???
 * @return ??
 */
public static Map<String, String> sendPost(String url, String param, String sessionId) {
    Map<String, String> resultMap = new HashMap<String, String>();
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        if (StringUtils.isNotBlank(sessionId)) {
            conn.setRequestProperty("Cookie", sessionId);
        }
        // ??POST
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // ?URLConnection?
        out = new PrintWriter(conn.getOutputStream());
        // ???
        out.print(param);
        // flush?
        out.flush();
        // BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String cookieValue = conn.getHeaderField("Set-Cookie");
        resultMap.put("cookieValue", cookieValue);
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("?? POST ?" + e);
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    resultMap.put("result", result);
    return resultMap;
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testHeaderAddedInMessageBody() throws Exception {
    final String serverHeaderValue = "Ad-Hoc testing server";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {

            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {

                        response.setHeader(HeaderName.SERVER, serverHeaderValue);
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }/*  w  w w .  j a v  a  2 s .  co  m*/
                    ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes());
                    out.write(bb);
                }
            });
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.connect();
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(serverHeaderValue, connection.getHeaderField("server"));
        connection.getContentLength();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void wrongPasswordDontSave() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid//  ww  w. j a  va  2  s.  com
    userRealm.put(USERNAME, PASSWORD2);
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD);
    assertFalse("Should not be set to save by default", usernamePassword.isShouldSave());
    //FixedPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Should have asked provider as much as authenticator", authenticator.calls,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Update provider to now provide the right one
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, PASSWORD2));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD2));
    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("id not called our password provider once", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}