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.ProtocolOcspHttpStandaloneTest.java

/**
 * Just verify that a both escaped and non-encoded GET requests work.
 *//* ww w .  j av a2 s. c  o m*/
@Test
public void test13GetRequests() throws Exception {
    super.test13GetRequests();
    // See if the OCSP Servlet can also read escaped requests
    final String urlEncReq = httpReqPath + '/' + resourceOcsp + '/'
            + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB%2BAevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCCzdx5N0v9XwoiEwHzAdBgkrBgEFBQcwAQIEECrZswo%2Fa7YW%2Bhyi5Sn85fs%3D";
    URL url = new URL(urlEncReq);
    log.info(url.toString()); // Dump the exact string we use for access
    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());
    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 dubbleSlashEncReq = httpReqPath + '/' + resourceOcsp + '/'
            + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB%2BAevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCAvB%2F%2FHJyKqpoiEwHzAdBgkrBgEFBQcwAQIEEOTzT2gv3JpVva22Vj8cuKo%3D";
    url = new URL(dubbleSlashEncReq);
    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());
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read an error response from the given connection and throw a
* suitable {@link HttpClientException}. This method always throws an
* exception, it will never return normally.
*///from  w  w w  .j  a va  2s. com
private void readError(HttpURLConnection connection) throws HttpClientException {
    InputStream stream;
    try {
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");

        try {
            JsonNode errorNode = null;
            if (connection.getContentType().contains("json")) {
                errorNode = MAPPER.readTree(stream);
            } else if (connection.getContentType().contains("xml")) {
                errorNode = XML_MAPPER.readTree(stream);
            }

            throw new HttpClientException("Server returned response code " + connection.getResponseCode(),
                    errorNode);

        } finally {
            reader.close();
        }
    } catch (HttpClientException e2) {
        throw e2;
    } catch (Exception e2) {
        throw new HttpClientException("Error communicating with server", e2);
    }
}

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

/**
 *
 * @param ocspPackage//  w  w w  .  jav  a  2 s.  c  o m
 * @param nonce
 * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked.
 * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example
 * @return a BasicOCSPResp or null if not found
 * @throws IOException
 * @throws OCSPException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException on parsing errors.
 * @throws OperatorCreationException 
 */
protected BasicOCSPResp sendOCSPGet(byte[] ocspPackage, String nonce, int respCode, int httpCode,
        boolean shouldIncludeSignCert, X509Certificate signCert) throws IOException, OCSPException,
        NoSuchProviderException, NoSuchAlgorithmException, OperatorCreationException, CertificateException {
    // GET the OCSP request
    String b64 = new String(Base64.encode(ocspPackage, false));
    //String urls = URLEncoder.encode(b64, "UTF-8");   // JBoss/Tomcat will not accept escaped '/'-characters by default
    URL url = new URL(this.sBaseURL + '/' + b64 + this.urlEnding);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    if (con.getResponseCode() != httpCode) {
        log.info("URL when request gave unexpected result: " + url.toString() + " Message was: "
                + con.getResponseMessage());
    }
    assertEquals("Response code did not match. ", httpCode, con.getResponseCode());
    if (con.getResponseCode() != 200) {
        return null; // if it is an http error code we don't need to test any more
    }
    // 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()));
    assertNotNull("Response should not be null.", response);
    assertEquals("Response status not the expected.", respCode, response.getStatus());
    if (respCode != 0) {
        assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject());
        return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses
    }
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();

    final X509CertificateHolder signCertHolder;
    if (!shouldIncludeSignCert) {
        assertEquals("The signing certificate should not be included in the OCSP response ", 0,
                brep.getCerts().length);
        signCertHolder = new JcaX509CertificateHolder(signCert);
    } else {
        X509CertificateHolder[] chain = brep.getCerts();
        signCertHolder = chain[0];
    }
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signCertHolder));

    assertTrue("Response failed to verify.", verify);
    // Check nonce (if we sent one)
    if (nonce != null) {
        byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
                .getEncoded();
        assertNotNull(noncerep);
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        assertEquals(nonce, new String(oct.getOctets()));
    }
    return brep;
}

From source file:org.holistic.ws_proxy.WSProxyHelper.java

private void doPost(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    HttpURLConnection m_objURLConnection = null;
    m_objURLConnection = openurl(get_request(req));
    // resp.setStatus(m_objURLConnection.getResponseCode());

    m_objURLConnection.setDoOutput(true);
    m_objURLConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
    set_headers2urlconn(req, m_objURLConnection);
    m_objURLConnection.setRequestProperty("host",
            m_objURLConnection.getURL().getHost() + ":" + m_objURLConnection.getURL().getPort());
    PrintWriter m_objOutput = new PrintWriter(m_objURLConnection.getOutputStream());
    m_objOutput.print(get_postdata(req));
    m_objOutput.close();/*from   w  ww .  jav  a  2 s.c o m*/

    resp.setStatus(m_objURLConnection.getResponseCode());
    if (m_objURLConnection.getContentType() != null)
        resp.setContentType(m_objURLConnection.getContentType());
    get_endpointstream(resp, m_objURLConnection);
}

From source file:com.boxupp.utilities.PuppetUtilities.java

public StatusBean downloadModule(JsonNode moduleData) {
    Gson searchModuleData = new GsonBuilder().setDateFormat("yyyy'-'MM'-'dd HH':'mm':'ss").create();
    SearchModuleBean searchModuleBean = searchModuleData.fromJson(moduleData.toString(),
            SearchModuleBean.class);
    String fileURL = CommonProperties.getInstance().getPuppetForgeDownloadAPIPath()
            + searchModuleBean.getCurrent_release().getFile_uri();
    StatusBean statusBean = new StatusBean();
    URL url = null;/*from   ww w  .  jav  a  2s.c o  m*/
    int responseCode = 0;
    HttpURLConnection httpConn = null;
    String fileSeparator = OSProperties.getInstance().getOSFileSeparator();
    String moduleDirPath = constructModuleDirectory() + fileSeparator;
    checkIfDirExists(new File(constructManifestsDirectory()));
    checkIfDirExists(new File(moduleDirPath));
    try {
        url = new URL(fileURL);
        httpConn = (HttpURLConnection) url.openConnection();
        responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 9, disposition.length());
                }
            } else {
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
            }
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = moduleDirPath + fileName;
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            extrectFile(saveFilePath, moduleDirPath, searchModuleBean.getModuleName());
            File file = new File(saveFilePath);
            file.delete();

        } else {
            logger.error("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
        statusBean.setStatusCode(0);
        statusBean.setStatusMessage(" Module Downloaded successfully ");
    } catch (IOException e) {
        logger.error("Error in loading module :" + e.getMessage());
        statusBean.setStatusCode(1);
        statusBean.setStatusMessage("Error in loading module :" + e.getMessage());
    }
    statusBean = PuppetModuleDAOManager.getInstance().create(moduleData);
    return statusBean;
}

From source file:org.apache.flink.runtime.webmonitor.WebFrontendITCase.java

@Test
public void testResponseHeaders() throws Exception {
    // check headers for successful json response
    URL taskManagersUrl = new URL("http://localhost:" + getRestPort() + "/taskmanagers");
    HttpURLConnection taskManagerConnection = (HttpURLConnection) taskManagersUrl.openConnection();
    taskManagerConnection.setConnectTimeout(100000);
    taskManagerConnection.connect();/*from w  ww.j a va2  s  .  c om*/
    if (taskManagerConnection.getResponseCode() >= 400) {
        // error!
        InputStream is = taskManagerConnection.getErrorStream();
        String errorMessage = IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET);
        throw new RuntimeException(errorMessage);
    }

    // we don't set the content-encoding header
    Assert.assertNull(taskManagerConnection.getContentEncoding());
    Assert.assertEquals("application/json; charset=UTF-8", taskManagerConnection.getContentType());

    // check headers in case of an error
    URL notFoundJobUrl = new URL("http://localhost:" + getRestPort() + "/jobs/dontexist");
    HttpURLConnection notFoundJobConnection = (HttpURLConnection) notFoundJobUrl.openConnection();
    notFoundJobConnection.setConnectTimeout(100000);
    notFoundJobConnection.connect();
    if (notFoundJobConnection.getResponseCode() >= 400) {
        // we don't set the content-encoding header
        Assert.assertNull(notFoundJobConnection.getContentEncoding());
        Assert.assertEquals("application/json; charset=UTF-8", notFoundJobConnection.getContentType());
    } else {
        throw new RuntimeException("Request for non-existing job did not return an error.");
    }
}

From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java

public String downloadDatabase() {
    boolean flag = false;
    HttpURLConnection urlConnection = null;
    OutputStream myOutput = null;
    byte[] buffer = null;
    InputStream inputStream = null;
    String message = FAIL;/* www. j a  va2  s .  c o m*/
    System.out.print(downloadDBURL);
    try {
        URL url = new URL(downloadDBURL);
        urlConnection = (HttpURLConnection) url.openConnection();
        System.out.println("##Request Sent...");

        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(20000);
        urlConnection.setReadTimeout(10000);
        urlConnection.connect();

        int Http_Result = urlConnection.getResponseCode();
        String res = urlConnection.getResponseMessage();
        System.out.println(res);
        System.out.println(String.valueOf(Http_Result));
        if (Http_Result == HttpURLConnection.HTTP_OK) {
            String contentType = urlConnection.getContentType();
            inputStream = urlConnection.getInputStream();
            System.out.println(contentType);
            if (contentType.equals("application/octet-stream")) {
                buffer = new byte[1024];
                myOutput = new FileOutputStream(this.dbFile);
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                myOutput.flush();
                myOutput.close();
                inputStream.close();
                flag = true;
                message = SUCCESS;
            } else if (contentType.equals("application/json; charset=UTF-8")) {
                message = FAIL;
                flag = false;
                String responce = convertStreamToString(inputStream);
                System.out.println(responce);

                try {
                    JSONObject jsResponce = new JSONObject(responce);
                    message = jsResponce.getString("message");
                } catch (JSONException e) {
                    // addError(screenName, "Json error in downloadDatabase", e.getMessage());
                    System.out.println(e.toString());
                }
            }
        }

    } catch (Exception ex) {
        System.out.println("##ROrder while downloading database" + ex.toString());
        //addError(screenName, "downloadDatabase", ex.getMessage());
    }
    return message;
}

From source file:org.nuxeo.http.blobprovider.HttpBlobProvider.java

/**
 * Sends a HEAD request to get the info without downloading the file.
 * <p>//from ww w  . java  2s. c om
 * If an error occurs, returns null.
 *
 * @param urlStr
 * @return the BlobInfo
 * @since 8.1
 */
public BlobInfo guessInfosFromURL(String urlStr) {

    BlobInfo bi = null;
    String attrLowerCase;
    try {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        addHeaders(connection, urlStr);

        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {

            bi = new BlobInfo();

            bi.mimeType = connection.getContentType();
            // Remove possible ...;charset="something"
            int idx = bi.mimeType.indexOf(";");
            if (idx >= 0) {
                bi.mimeType = bi.mimeType.substring(0, idx);
            }

            bi.encoding = connection.getContentEncoding();
            bi.length = connection.getContentLengthLong();
            if (bi.length < 0) {
                bi.length = 0L;
            }

            String disposition = connection.getHeaderField("Content-Disposition");
            String fileName = null;
            if (disposition != null) {
                String[] attributes = disposition.split(";");

                for (String attr : attributes) {
                    attrLowerCase = attr.toLowerCase();
                    if (attrLowerCase.contains("filename=")) {
                        attr = attr.trim();
                        // Remove filename=
                        fileName = attr.substring(9);
                        idx = fileName.indexOf("\"");
                        if (idx > -1) {
                            fileName = fileName.substring(idx + 1, fileName.lastIndexOf("\""));
                        }
                        bi.filename = fileName;
                        break;

                    } else if (attrLowerCase.contains("filename*=utf-8''")) {
                        attr = attr.trim();
                        // Remove filename=
                        fileName = attr.substring(17);
                        idx = fileName.indexOf("\"");
                        if (idx > -1) {
                            fileName = fileName.substring(idx + 1, fileName.lastIndexOf("\""));
                        }
                        fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
                        bi.filename = fileName;
                        break;
                    }
                }
            } else {
                // Try from the url
                idx = urlStr.lastIndexOf("/");
                if (idx > -1) {
                    fileName = urlStr.substring(idx + 1);
                    bi.filename = java.net.URLDecoder.decode(fileName, "UTF-8");
                }
            }
        }

    } catch (Exception e) { // Whatever the error, we fail. No need to be
        // granular here.
        bi = null;
    }

    return bi;
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceTest.java

@Test
@RunAsClient/*ww  w  . ja v a  2  s  .c o m*/
public void testGetAssetSource(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/source");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.TEXT_PLAIN);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection.getContentType());
    String result = IOUtils.toString(connection.getInputStream());
    assertTrue(result.indexOf("declare Album2") >= 0);
    assertTrue(result.indexOf("genre2: String") >= 0);
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceTest.java

@Test
@RunAsClient/*from   w w w  . ja  v  a2  s  .co  m*/
public void testGetAssetAsJaxB(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_XML, connection.getContentType());
    System.out.println(IOUtils.toString(connection.getInputStream()));
}