Example usage for java.net HttpURLConnection getContent

List of usage examples for java.net HttpURLConnection getContent

Introduction

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

Prototype

public Object getContent() throws IOException 

Source Link

Document

Retrieves the contents of this URL connection.

Usage

From source file:controller.CCInstance.java

private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert)
        throws GeneralSecurityException, OCSPException, IOException, OperatorException {
    if (checkCert == null || rootCert == null) {
        return null;
    }//from   w w w.java 2  s. c  o  m
    String url = CertificateUtil.getOCSPURL(checkCert);

    if (url == null) {
        return null;
    }
    try {
        OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
        byte[] array = request.getEncoded();
        URL urlt = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlt.openConnection();
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        con.setDoOutput(true);

        OutputStream out = con.getOutputStream();
        try (DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out))) {
            dataOut.write(array);
            dataOut.flush();
        }

        if (con.getResponseCode() / 100 != 2) {
            throw new IOException(
                    MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
        }
        //Get Response
        InputStream in = (InputStream) con.getContent();
        return new OCSPResp(in);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
 * @param String request/*from  ww w . j  ava  2  s . c  o  m*/
 * @param String httpMethod
 * @return String
 */
private String getResponse(String request, String httpMethod)
        throws MalformedURLException, IOException, PlancakeApiException {
    if (!(httpMethod.equals("GET")) && !(httpMethod.equals("POST"))) {
        throw new PlancakeApiException("httpMethod must be either GET or POST");
    }

    String urlParameters = "";

    if (httpMethod == "POST") {
        String[] requestParts = request.split("\\?");
        request = requestParts[0];
        urlParameters = requestParts[1];
    }

    URL url = new URL(request);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(httpMethod);
    if (httpMethod == "POST") {
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    } else {
        connection.setRequestProperty("Content-Type", "text/plain");
    }
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches(false);
    connection.connect();

    if (httpMethod == "POST") {
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }

    StringBuffer text = new StringBuffer();
    InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
    BufferedReader buff = new BufferedReader(in);
    String line = buff.readLine();
    while (line != null) {
        text.append(line + "\n");
        line = buff.readLine();
    }
    String response = text.toString();

    if (response.length() == 0) {
        throw new PlancakeApiException("the response is empty");
    }

    connection.disconnect();
    return response;
}

From source file:org.kie.tests.wb.base.methods.KieWbRestIntegrationTestMethods.java

public void urlsHttpURLConnectionAcceptHeaderIsFixed(URL deploymentUrl, String user, String password)
        throws Exception {
    URL url = new URL(deploymentUrl, deploymentUrl.getPath() + "rest/runtime/" + deploymentId + "/process/"
            + SCRIPT_TASK_PROCESS_ID + "/start");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    String authString = user + ":" + password;
    byte[] bytes = authString.getBytes();
    String authStringEnc = Base64Util.encode(bytes, 0, bytes.length);
    connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    connection.setRequestMethod("POST");

    logger.debug(">> [POST] " + url.toExternalForm());
    connection.connect();//from   w ww  .ja v  a2s.  c  o m
    if (200 != connection.getResponseCode()) {
        logger.warn(connection.getContent().toString());
    }
    assertEquals(200, connection.getResponseCode());
}

From source file:org.kie.tests.wb.base.methods.KieWbRestIntegrationTestMethods.java

public void urlsGetDeployments(URL deploymentUrl, String user, String password) throws Exception {
    setRestInfo(deploymentUrl, user, password);
    // test with normal RequestCreator

    JaxbDeploymentUnitList depList = get("deployment/", 200, JaxbDeploymentUnitList.class);
    assertNotNull("Null answer!", depList);
    assertNotNull("Null deployment list!", depList.getDeploymentUnitList());
    assertTrue("Empty deployment list!", depList.getDeploymentUnitList().size() > 0);

    String deploymentId = depList.getDeploymentUnitList().get(0).getIdentifier();
    JaxbDeploymentUnit dep = get("deployment/" + deploymentId, 200, JaxbDeploymentUnit.class);
    assertNotNull("Null answer!", dep);
    assertNotNull("Null deployment list!", dep);
    assertEquals("Empty status!", JaxbDeploymentStatus.DEPLOYED, dep.getStatus());

    // test with HttpURLConnection
    URL url = new URL(deploymentUrl, deploymentUrl.getPath() + "rest/deployment/");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    String authString = user + ":" + password;
    byte[] authStrBytes = authString.getBytes();
    String authStringEnc = Base64Util.encode(authStrBytes, 0, authStrBytes.length);
    connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    connection.setRequestMethod("GET");

    logger.debug(">> [GET] " + url.toExternalForm());
    connection.connect();//from   w ww  .j  av a 2 s . c o m
    int respCode = connection.getResponseCode();
    if (200 != respCode) {
        logger.warn(connection.getContent().toString());
    }
    assertEquals(200, respCode);

    JaxbSerializationProvider jaxbSerializer = ClientJaxbSerializationProvider.newInstance();
    String xmlStrObj = getConnectionContent(connection.getContent());
    logger.info("Output: |" + xmlStrObj + "|");
    depList = (JaxbDeploymentUnitList) jaxbSerializer.deserialize(xmlStrObj);

    assertNotNull("Null answer!", depList);
    assertNotNull("Null deployment list!", depList.getDeploymentUnitList());
    assertTrue("Empty deployment list!", depList.getDeploymentUnitList().size() > 0);
}

From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public long newProcessInstance(String deploymentId, String processId, Map<String, Object> context)
        throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override//ww w .ja  v a2  s .  com
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        deploymentId = URLEncoder.encode(deploymentId, "UTF-8"); //$NON-NLS-1$
        processId = URLEncoder.encode(processId, "UTF-8"); //$NON-NLS-1$
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/start/%s/%s", deploymentId, processId); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        StringBuffer params = new StringBuffer();
        for (String key : context.keySet()) {
            String value = String.valueOf(context.get(key));
            value = URLEncoder.encode(value, "UTF-8"); //$NON-NLS-1$
            params.append(String.format("&%s=%s", key, value)); //$NON-NLS-1$
        }
        //remove leading '&'
        if (params.length() > 0)
            params.delete(0, 1);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        if (params.length() > 0) {
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params.toString());
            out.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            logger.info("reply=" + reply); //$NON-NLS-1$
            return Long.parseLong(reply);
        } else {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

/**
 * Implement a simple proxy/*from  ww w .j  a v  a 2  s .c  o m*/
 *
 * @param requestedURL the requested URL
 * @param req the HttpServletRequest
 * @return
 */
@GET
@Path("proxy")
public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL,
        @Context HttpServletRequest req) {

    BufferedReader in = null;

    try {
        URL url = new URL(requestedURL);
        URLConnection urlConnection = url.openConnection();

        int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout();

        // Set base properties
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec

        String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);
        if (StringUtils.isNotBlank(acceptedDataFormat)) {
            urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat);
        }

        // Open the connection
        urlConnection.connect();

        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;

            int statusCode = httpConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // Follow the redirect
                String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION);
                httpConnection.disconnect();

                if (StringUtils.isNotBlank(newLocation)) {
                    return this.proxy(newLocation, req);
                } else {
                    return Response.status(statusCode).build();
                }
            } else if (statusCode == HttpURLConnection.HTTP_OK) {

                // Send the response
                StringBuilder sbf = new StringBuilder();

                // Check if the contentType is supported
                boolean contentTypeSupported = false;
                String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE);
                List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes();
                if (contentType != null) {
                    for (String cMime : supportedMimeTypes) {
                        if (contentType.equals(cMime) || contentType.contains(cMime)) {
                            contentTypeSupported = true;
                            break;
                        }
                    }
                }

                if (!contentTypeSupported) {
                    httpConnection.disconnect();
                    return Response.status(Status.NOT_ACCEPTABLE).build();
                }

                String contentEncoding = httpConnection.getContentEncoding();
                if (StringUtils.isBlank(contentEncoding)) {
                    contentEncoding = "UTF-8";
                }

                InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(),
                        Charset.forName(contentEncoding));
                in = new BufferedReader(inStrem);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sbf.append(inputLine);
                    sbf.append("\r\n");
                }

                in.close();
                httpConnection.disconnect();

                return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType)
                        .entity(sbf.toString()).build();

            } else {
                httpConnection.disconnect();
                return Response.status(statusCode).build();
            }
        }

        return Response.status(Status.BAD_REQUEST).build();

    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.BAD_REQUEST).build();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

protected static OCSPResp getOCSPResponse(String serviceUrl, OCSPReq request) throws Exception {
    try {/*from   w w  w . j  av  a  2 s . c  o  m*/
        //Todo: Use http client.
        byte[] array = request.getEncoded();
        if (serviceUrl.startsWith("http")) {
            HttpURLConnection con;
            URL url = new URL(serviceUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Content-Type", "application/ocsp-request");
            con.setRequestProperty("Accept", "application/ocsp-response");
            con.setDoOutput(true);
            OutputStream out = con.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
            dataOut.write(array);

            dataOut.flush();
            dataOut.close();

            //Check errors in response:
            if (con.getResponseCode() / 100 != 2) {
                throw new Exception(
                        "Error getting ocsp response." + "Response code is " + con.getResponseCode());
            }

            //Get Response
            InputStream in = (InputStream) con.getContent();
            return new OCSPResp(in);
        } else {
            throw new Exception("Only http is supported for ocsp calls");
        }
    } catch (IOException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        throw new Exception("Cannot get ocspResponse from url: " + serviceUrl, ex);
    }
}