Example usage for java.net HttpURLConnection getContentType

List of usage examples for java.net HttpURLConnection getContentType

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Returns the value of the content-type header field.

Usage

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/**
 * Tests request for a pkcs12//w  w  w . j av a2 s  .c  o  m
 * 
 * @throws Exception error
 */
@Test
public void test01RequestPKCS12() throws Exception {
    log.trace(">test01RequestPKCS12()");

    // find a CA (TestCA?) create a user
    // Send certificate request for a server generated PKCS12
    setupUser(SecConst.TOKEN_SOFT_P12);
    setupUserStatus(EndEntityConstants.STATUS_NEW);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    os.write(("user=" + TEST_USERNAME + "&password=foo123&keylength=2048").getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/x-pkcs12; charset=UTF-8"
    String contentType = con.getContentType();
    boolean contentTypeIsPkcs12 = contentType.startsWith("application/x-pkcs12");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS12 requests are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);
    if (!contentTypeIsPkcs12 && log.isDebugEnabled()) {
        // If the content-type isn't application/x-pkcs12 we like to know what we got back..
        log.debug(new String(respBytes));
    }
    assertTrue("contentType was " + contentType, contentTypeIsPkcs12);

    KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    ByteArrayInputStream is = new ByteArrayInputStream(respBytes);
    store.load(is, "foo123".toCharArray());
    assertTrue(store.containsAlias("ReqTest"));
    X509Certificate cert = (X509Certificate) store.getCertificate("ReqTest");
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
        assertEquals(2048, rsapk.getModulus().bitLength());
    } else {
        assertTrue("Public key is not RSA", false);
    }

    log.trace("<test01RequestPKCS12()");
}

From source file:org.dcm4che2.tool.dcmwado.DcmWado.java

private void fetch(String[] uids) {
    URL url = makeURL(uids);//  www. j av  a  2s. c o m
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(followsRedirect);
        con.setRequestProperty("Connection", "Keep-Alive");
        con.connect();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = con.getInputStream();
            if (dir != null) {
                out = new FileOutputStream(
                        outfile != null ? (outfile.isAbsolute() ? outfile : new File(dir, outfile.getPath()))
                                : new File(dir, uids[2] + toFileExt(con.getContentType())));
            }
            copy(in, out);
        } finally {
            CloseUtils.safeClose(out);
            CloseUtils.safeClose(in);
            if (noKeepAlive)
                con.disconnect();
        }
        System.out.print('.');
    } catch (Exception e) {
        System.err.println("ERROR: Failed to GET " + url + " - " + e.getMessage());
        e.printStackTrace();
        System.out.print('F');
    }
}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Create an Atom enclosure element for the resource (usually podcast or other
 * multimedia) at the specified URL.//from  w w  w .ja v  a  2s.c  om
 *
 * @param url web URL where the resource is located.
 * @return AtomEnclosure element for the resource
 */
public AtomEnclosure generateEnclosure(String url) {
    if (url == null || url.trim().length() == 0) {
        return null;
    }

    AtomEnclosure resource;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        int response = con.getResponseCode();
        String message = con.getResponseMessage();

        if (response != 200) {
            // Bad Response
            log.debug("Mediacast error {}:{} from url {}", response, message, url);
            throw new IllegalArgumentException("entryEdit.mediaCastResponseError");
        } else {
            String contentType = con.getContentType();
            long length = con.getContentLength();

            if (contentType == null || length == -1) {
                // Incomplete
                log.debug("Response valid, but contentType or length is invalid");
                throw new IllegalArgumentException("entryEdit.mediaCastLacksContentTypeOrLength");
            }

            resource = new AtomEnclosure(url, contentType, length);
            log.debug("Valid mediacast resource = {}", resource.toString());

        }
    } catch (MalformedURLException mfue) {
        // Bad URL
        log.debug("Malformed MediaCast url: {}", url);
        throw new IllegalArgumentException("entryEdit.mediaCastUrlMalformed", mfue);
    } catch (Exception e) {
        // Check Failed
        log.error("ERROR while checking MediaCast URL: {}: {}", url, e.getMessage());
        throw new IllegalArgumentException("entryEdit.mediaCastFailedFetchingInfo", e);
    }
    return resource;
}

From source file:org.y20k.transistor.core.Station.java

private ContentType getContentType(URL fileLocation) {
    try {//from w  w  w.j  av a2 s .co  m
        HttpURLConnection connection = (HttpURLConnection) fileLocation.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        String contentTypeHeader = connection.getContentType();

        if (contentTypeHeader != null) {
            Matcher matcher = CONTENT_TYPE_PATTERN
                    .matcher(contentTypeHeader.trim().toLowerCase(Locale.ENGLISH));
            if (matcher.matches()) {
                ContentType contentType = new ContentType();
                String contentTypeString = matcher.group(1);
                String charsetString = matcher.group(3);
                if (contentTypeString != null) {
                    contentType.type = contentTypeString.trim();
                }
                if (charsetString != null) {
                    contentType.charset = charsetString.trim();
                }
                return contentType;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

@Test
public void test10ScepGetCACaps() throws Exception {
    String reqUrl = httpReqPath + '/' + resourceScep + "?operation=GetCACaps&message="
            + URLEncoder.encode(x509ca.getName(), "UTF-8");
    URL url = new URL(reqUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.getDoOutput();/*w  w  w  .  j av a2  s  .c om*/
    con.connect();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with "text/plain; charset=UTF-8"
    assertTrue(con.getContentType().startsWith("text/plain"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and SCEP requests are small enough
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertNotNull("Response can not be null.", respBytes);
    assertTrue(respBytes.length > 0);
    assertEquals(new String(respBytes), "POSTPKIOperation\nRenewal\nSHA-1");
}

From source file:org.ecoinformatics.datamanager.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * //w w  w  .j  ava2  s.  c o  m
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:edu.lternet.pasta.dml.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * //from w w  w  .  java2 s  .  com
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param urlConn//w w  w. ja v  a  2 s.c o  m
 * @return
 */
private String getSourceContentType(HttpURLConnection urlConn) {

    // prefer content type from context source DTO over the one from URL connection
    String contentType = getContextSourceDTO().getMediaType();
    if (StringUtils.isBlank(contentType)) {
        contentType = urlConn.getContentType();
    }
    return contentType;
}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

@Test
public void test08ScepGetCACert() throws Exception {
    {//from   w w w.  j  a v  a 2 s  .  co m
        String reqUrl = httpReqPath + '/' + resourceScep + "?operation=GetCACert&message="
                + URLEncoder.encode(x509ca.getName(), "UTF-8");
        URL url = new URL(reqUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 200 (OK)", 200, con.getResponseCode());
        // Some appserver (Weblogic) responds with
        // "application/x-x509-ca-cert; charset=UTF-8"
        assertTrue(con.getContentType().startsWith("application/x-x509-ca-cert"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and SCEP requests are small enough
        InputStream in = con.getInputStream();
        int b = in.read();
        while (b != -1) {
            baos.write(b);
            b = in.read();
        }
        baos.flush();
        in.close();
        byte[] respBytes = baos.toByteArray();
        assertNotNull("Response can not be null.", respBytes);
        assertTrue(respBytes.length > 0);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(respBytes);
        // Check that we got the right cert back
        assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName());
    }

    // 
    // Test the same message but without message component, it should use a default CA
    {
        // Try with a non extisting CA first, should respond with a 404
        updatePropertyOnServer("scep.defaultca", "NonExistingCAForSCEPTest");
        String reqUrl = httpReqPath + '/' + resourceScep + "?operation=GetCACert";
        URL url = new URL(reqUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 404 (not found)", 404, con.getResponseCode());
        // Try with the good CA            
        updatePropertyOnServer("scep.defaultca", x509ca.getName());
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.getDoOutput();
        con.connect();
        assertEquals("Response code is not 200 (OK)", 200, con.getResponseCode());
        // Some appserver (Weblogic) responds with
        // "application/x-x509-ca-cert; charset=UTF-8"
        assertTrue(con.getContentType().startsWith("application/x-x509-ca-cert"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and SCEP requests are small enough
        InputStream in = con.getInputStream();
        int b = in.read();
        while (b != -1) {
            baos.write(b);
            b = in.read();
        }
        baos.flush();
        in.close();
        byte[] respBytes = baos.toByteArray();
        assertNotNull("Response can not be null.", respBytes);
        assertTrue(respBytes.length > 0);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(respBytes);
        // Check that we got the right cert back
        assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName());
    }
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getURLOnly(WebLink url) {

    log.debug("getURL(" + url + ")");

    if (url.getUrlStr() == null) {
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(null, null, conRes, null);
    }//w w  w .ja va 2s. c  om

    URL requestedURL = null;
    URL referer = null;
    try {
        requestedURL = new URL(url.getUrlStr());
        log.debug("Creating HTTP connection to " + requestedURL);
        HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection();
        if (referer != null) {
            log.debug("Setting Referer header to " + referer);
            conn.setRequestProperty("Referer", referer.toExternalForm());
        }

        if (userAgent != null) {
            log.debug("Setting User-Agent to " + userAgent);
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setUseCaches(false);

        log.debug("Opening URL");
        long startTime = System.currentTimeMillis();
        conn.connect();

        String resp = conn.getResponseMessage();
        log.debug("Remote server response: " + resp);

        int code = conn.getResponseCode();

        if (code != 200) {
            log.error("Could not get connection for code=" + code);
            System.err.println("Could not get connection for code=" + code);
        }
        ConnResponse conRes = new ConnResponse(conn.getContentType(), null, 0, 0, code);
        conn.disconnect();
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, conRes.getCharSet());
    }

    catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    } catch (Exception e) {
        log.warn("Caught Exception: " + e.getMessage(), e);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    }
}