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.core.protocol.ocsp.ProtocolOcspTestBase.java

/**
 * Just verify that a simple GET works./*w w  w  .  j a  v  a2  s .c  om*/
 */
protected void test13GetRequests() throws Exception { // NOPMD, this is not a test class itself
    loadUserCert(this.caid);
    // See if the OCSP Servlet can read non-encoded requests
    final String plainReq = httpReqPath + '/' + resourceOcsp + '/'
            + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB+Aevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCCzdx5N0v9XwoiEwHzAdBgkrBgEFBQcwAQIEECrZswo/a7YW+hyi5Sn85fs=";
    URL url = new URL(plainReq);
    log.info(url.toString()); // Dump the exact string we use for access
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    assertEquals("Response code did not match. ", 200, con.getResponseCode());
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertNotNull("Response should not be null.", response);
    assertTrue("Should not be concidered malformed.",
            OCSPRespBuilder.MALFORMED_REQUEST != response.getStatus());
    final String dubbleSlashNonEncReq = httpReqPath + '/' + resourceOcsp + '/'
            + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB%2BAevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCAvB//HJyKqpoiEwHzAdBgkrBgEFBQcwAQIEEOTzT2gv3JpVva22Vj8cuKo%3D";
    url = new URL(dubbleSlashNonEncReq);
    log.info(url.toString()); // Dump the exact string we use for access
    con = (HttpURLConnection) url.openConnection();
    assertEquals("Response code did not match. ", 200, con.getResponseCode());
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertNotNull("Response should not be null.", response);
    assertTrue("Should not be concidered malformed.",
            OCSPRespBuilder.MALFORMED_REQUEST != response.getStatus());
    // An OCSP request, ocspTestCert is already created in earlier tests
    OCSPReqBuilder gen = new OCSPReqBuilder();
    loadUserCert(this.caid);
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()));
    OCSPReq req = gen.build();
    BasicOCSPResp brep = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    SingleResp[] singleResps = brep.getResponses();
    assertNotNull("SingleResps should not be null.", singleResps);
    CertificateID certId = singleResps[0].getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
            ocspTestCert.getSerialNumber());
    Object status = singleResps[0].getCertStatus();
    assertEquals("Status is not null (null is 'good')", null, status);
}

From source file:com.github.mobile.util.HttpImageGetter.java

@Override
public Drawable getDrawable(String source) {
    Bitmap bitmap = null;/*from   ww w  . jav a2  s.com*/

    if (!destroyed) {
        File output = null;
        InputStream is = null;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(source).openConnection();
            is = connection.getInputStream();
            if (is != null) {
                String mime = connection.getContentType();
                if (mime == null) {
                    mime = URLConnection.guessContentTypeFromName(source);
                }
                if (mime == null) {
                    mime = URLConnection.guessContentTypeFromStream(is);
                }
                if (mime != null && mime.startsWith("image/svg")) {
                    bitmap = ImageUtils.renderSvgToBitmap(context.getResources(), is, width, height);
                } else {
                    boolean isGif = mime != null && mime.startsWith("image/gif");
                    if (!isGif || canLoadGif()) {
                        output = File.createTempFile("image", ".tmp", dir);
                        if (FileUtils.save(output, is)) {
                            if (isGif) {
                                GifDrawable d = new GifDrawable(output);
                                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                                return d;
                            } else {
                                bitmap = ImageUtils.getBitmap(output, width, height);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            // fall through to showing the loading bitmap
        } finally {
            if (output != null) {
                output.delete();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // ignored
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    synchronized (this) {
        if (destroyed && bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        } else if (bitmap != null) {
            loadedBitmaps.add(new WeakReference<>(bitmap));
        }
    }

    if (bitmap == null) {
        return loading.getDrawable(source);
    }

    BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
    drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
    return drawable;
}

From source file:org.nuxeo.labs.operations.services.HTTPDownloadFile.java

@OperationMethod
public Blob run() throws IOException {

    Blob result = null;/*  w  w w  .j  ava2 s .c  om*/

    HttpURLConnection http = null;
    String error = "";
    String resultStatus = "";
    boolean isUnknownHost = false;

    try {
        URL theURL = new URL(url);

        http = (HttpURLConnection) theURL.openConnection();
        HTTPUtils.addHeaders(http, headers, headersAsJSON);

        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {

            String fileName = "";
            String disposition = http.getHeaderField("Content-Disposition");
            String contentType = http.getContentType();
            String encoding = http.getContentEncoding();

            // Try to get a filename
            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > -1) {
                    fileName = disposition.substring(index + 9);
                }
            } else {
                // extracts file name from URL
                fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
            }
            if (StringUtils.isEmpty(fileName)) {
                fileName = "DownloadedFile-" + java.util.UUID.randomUUID().toString();
            }

            File tempFile = new File(
                    getTempFolderPath() + File.separator + java.util.UUID.randomUUID().toString());

            FileOutputStream outputStream = new FileOutputStream(tempFile);
            InputStream inputStream = http.getInputStream();
            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            result = new FileBlob(tempFile, contentType, encoding);
            result.setFilename(fileName);
        }

    } catch (Exception e) {

        error = e.getMessage();
        if (e instanceof java.net.UnknownHostException) {
            isUnknownHost = true;
        }

    } finally {
        int status = 0;
        String statusMessage = "";

        if (isUnknownHost) { // can't use our http variable
            status = 0;
            statusMessage = "UnknownHostException";
        } else {
            // Still, other failures _before_ reaching the server may occur
            // => http.getResponseCode() and others would throw an error
            try {
                status = http.getResponseCode();
                statusMessage = http.getResponseMessage();
            } catch (Exception e) {
                statusMessage = "Error getting the status message itself";
            }

        }

        ObjectMapper mapper = new ObjectMapper();
        ObjectNode resultObj = mapper.createObjectNode();
        resultObj.put("status", status);
        resultObj.put("statusMessage", statusMessage);
        resultObj.put("error", error);

        ObjectWriter ow = mapper.writer();// .withDefaultPrettyPrinter();
        resultStatus = ow.writeValueAsString(resultObj);
    }

    ctx.put("httpDownloadFileStatus", resultStatus);

    return result;
}

From source file:org.apache.hadoop.hbase.http.TestHttpServer.java

@Test
@Ignore//ww w. ja  v a 2s.  c o  m
public void testContentTypes() throws Exception {
    // Static CSS files should have text/css
    URL cssUrl = new URL(baseUrl, "/static/test.css");
    HttpURLConnection conn = (HttpURLConnection) cssUrl.openConnection();
    conn.connect();
    assertEquals(200, conn.getResponseCode());
    assertEquals("text/css", conn.getContentType());

    // Servlets should have text/plain with proper encoding by default
    URL servletUrl = new URL(baseUrl, "/echo?a=b");
    conn = (HttpURLConnection) servletUrl.openConnection();
    conn.connect();
    assertEquals(200, conn.getResponseCode());
    assertEquals("text/plain; charset=utf-8", conn.getContentType());

    // We should ignore parameters for mime types - ie a parameter
    // ending in .css should not change mime type
    servletUrl = new URL(baseUrl, "/echo?a=b.css");
    conn = (HttpURLConnection) servletUrl.openConnection();
    conn.connect();
    assertEquals(200, conn.getResponseCode());
    assertEquals("text/plain; charset=utf-8", conn.getContentType());

    // Servlets that specify text/html should get that content type
    servletUrl = new URL(baseUrl, "/htmlcontent");
    conn = (HttpURLConnection) servletUrl.openConnection();
    conn.connect();
    assertEquals(200, conn.getResponseCode());
    assertEquals("text/html; charset=utf-8", conn.getContentType());

    // JSPs should default to text/html with utf8
    servletUrl = new URL(baseUrl, "/testjsp.jsp");
    conn = (HttpURLConnection) servletUrl.openConnection();
    conn.connect();
    assertEquals(200, conn.getResponseCode());
    assertEquals("text/html; charset=utf-8", conn.getContentType());
}

From source file:me.futuretechnology.blops.ui.FeedFragment.java

private String getCharset(HttpURLConnection conn) {
    String contentType = conn.getContentType();
    String[] values = contentType.split(";"); // values.length must be equal to 2

    for (String value : values) {
        value = value.trim();//from w  w w .  j  a v a 2s  .c o m

        if (value.toLowerCase().startsWith("charset=")) {
            return value.substring("charset=".length());
        }
    }

    return "UTF-8"; // just in case...
}

From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket/*  ww  w . j  ava2 s .  c  om*/
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:de.kp.ames.web.function.access.wms.WmsConsumer.java

/**
 * Issues a request to the server and returns that 
 * server's response. It asks the server to send the 
 * response gzipped to provide a faster transfer time.
 * //w  w  w . j  av  a 2  s. c  o m
 * @param request
 * @return
 * @throws IOException
 * @throws ServiceException
 */
public Response sendRequest(Request request) throws IOException, ServiceException {

    // retrieve server url
    URL finalURL = request.getFinalURL();

    HttpURLConnection connection = (HttpURLConnection) finalURL.openConnection();
    connection.addRequestProperty("Accept-Encoding", "gzip");

    connection.setRequestMethod("GET");
    InputStream is = connection.getInputStream();

    if (connection.getContentEncoding() != null && connection.getContentEncoding().indexOf("gzip") != -1) {
        is = new GZIPInputStream(is);
    }

    String contentType = connection.getContentType();
    return request.createResponse(contentType, is);

}

From source file:org.apache.clerezza.integrationtest.web.performance.GetRdf.java

@Override
public void run() {

    try {/*from www. jav  a 2s  .c  o m*/
        URL url = new URL(resourceUri);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        try {
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept", "application/rdf+xml");
            con.setRequestProperty("Authorization", "Basic " + authString);
            con.setDoInput(true);

            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("GetRdf: (GET) unexpected " + "response code: " + responseCode);
            }

            String contentType = con.getContentType();
            if (contentType == null) {
                throw new RuntimeException("GetRdf: Couldn't determine content type.");
            }

            int length = con.getContentLength();
            byte[] content = new byte[length];
            InputStream inputStream = con.getInputStream();
            try {

                int i = 0;
                while (i < length && ((content[i++] = (byte) inputStream.read()) != -1)) {
                }
                if (i != length) {
                    throw new RuntimeException("GetRdf: Couldn't read all data.");
                }
                String contentStr = new String(content, getCharSet(contentType));

                if (!contentStr.contains(getInfoBitString(rdfResource))) {
                    throw new RuntimeException("GetRdf: Content does not contain expected information.");
                }
            } finally {
                inputStream.close();
            }
        } finally {
            con.disconnect();
        }
    } catch (MalformedURLException me) {
        me.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:org.apache.clerezza.integrationtest.web.performance.GetSparqlQuery.java

@Override
public void run() {
    try {/*from w w w  .j  a  v a 2s  .com*/
        String queryParams = URLEncoder.encode("query", UTF8) + "=" + URLEncoder.encode(query, UTF8);
        queryParams += "&";
        queryParams += URLEncoder.encode("default-graph-uri", UTF8) + "="
                + URLEncoder.encode("urn:x-localinstance:/content.graph", UTF8);
        URL url = new URL(requestUri + "?" + queryParams);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        try {
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept", "application/rdf+xml");
            con.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())));
            con.setDoOutput(true);

            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("GetSparqlQuery: unexpected " + "response code: " + responseCode);
            }
            String contentType = con.getContentType();
            if (contentType == null) {
                throw new RuntimeException("GetSparqlQuery: Couldn't determine content type.");
            }
            int length = con.getContentLength();
            byte[] content = new byte[length];
            InputStream inputStream = con.getInputStream();
            try {
                int i = 0;
                while (i < length && ((content[i++] = (byte) inputStream.read()) != -1)) {
                }
                if (i != length) {
                    throw new RuntimeException("GetSparqlQuery: Couldn't read all data.");
                }
            } finally {
                inputStream.close();
            }
        } finally {
            con.disconnect();
        }
    } catch (MalformedURLException me) {
        me.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:cm.aptoide.pt.util.NetworkUtils.java

public int checkServerConnection(final String string, final String username, final String password) {
    try {/*w  w  w. j a va 2 s.c  om*/

        HttpURLConnection client = (HttpURLConnection) new URL(string + "info.xml").openConnection();
        if (username != null && password != null) {
            String basicAuth = "Basic "
                    + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP));
            client.setRequestProperty("Authorization", basicAuth);
        }
        client.setConnectTimeout(TIME_OUT);
        client.setReadTimeout(TIME_OUT);
        if (ApplicationAptoide.DEBUG_MODE)
            Log.i("Aptoide-NetworkUtils-checkServerConnection", "Checking on: " + client.getURL().toString());
        if (client.getContentType().equals("application/xml")) {
            return 0;
        } else {
            return client.getResponseCode();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}