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:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java

private void checkStatus(ServiceType serviceStatus) {
    HttpURLConnection urlConnection = null;
    InputStream contentStream = null;
    InputStream countStream = null;
    try {//from   ww w. j  av a  2s. c o m

        final URL versionUrl = new URL(serviceStatus.getRestUrl() + "version");
        final URL countURL = new URL(serviceStatus.getRestUrl() + "query/*?format=count");

        urlConnection = (HttpURLConnection) versionUrl.openConnection();
        urlConnection.setConnectTimeout(threadTimeOut * 1000);
        urlConnection.setReadTimeout(threadTimeOut * 1000);

        urlConnection.connect();

        int code = urlConnection.getResponseCode();

        if (HttpURLConnection.HTTP_OK == code) {

            serviceStatus.setActive(true);

            final String version;
            final String strCount;

            //TODO Add a double check to know if the service is active
            // or not add a catch block for the exceptions

            contentStream = (InputStream) urlConnection.getContent();
            version = IOUtils.toString(contentStream);
            serviceStatus.setVersion(version);

            countStream = (InputStream) countURL.getContent();
            strCount = IOUtils.toString(countStream);
            serviceStatus.setCount(Long.valueOf(strCount));
        } else {
            serviceStatus.setActive(false);
        }

    } catch (Throwable e) {
        serviceStatus.setActive(false);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic content stream", e);
            }
        }
        if (countStream != null) {
            try {
                countStream.close();
            } catch (IOException e) {
                log.error("Cannot close psicquic count stream", e);
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.sakaiproject.content.chh.dspace.ContentHostingHandlerImplDSpace.java

private static final StringBuffer hitDSpaceWithRequest(String endpoint, StringBuffer requestXMLbuf)
        throws IOException {
    URL url = new URL(endpoint);
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    huc.setRequestMethod("GET");
    huc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    huc.setRequestProperty("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    huc.setRequestProperty("User-Agent", "Axis/1.3");
    // huc.setRequestProperty("Host","localhost:8081");
    huc.setRequestProperty("Cache-Control", "no-cache");
    huc.setRequestProperty("Pragma", "no-cache");
    huc.setRequestProperty("SOAPAction", "");
    huc.setRequestProperty("Content-Length", "" + requestXMLbuf.length());
    huc.setRequestProperty("Authorization",
            "Basic " + base64Encode(endpoint.substring(endpoint.indexOf("http://") + 7,
                    endpoint.indexOf("@", endpoint.indexOf("http://") + 7))));
    huc.setDoInput(true);/*from  w w  w.j  a  va  2 s .  c o  m*/
    huc.setDoOutput(true);
    huc.connect();
    huc.getOutputStream().write(requestXMLbuf.toString().getBytes());
    huc.getOutputStream().flush();
    huc.getContent();

    StringBuffer buf = new StringBuffer(1024);
    InputStream is = huc.getInputStream();
    for (;;) {
        byte b[] = new byte[256];
        int l = is.read(b);
        if (l > 0)
            buf.append(new String(b, 0, l));
        else
            break;
    }
    return buf;
}

From source file:org.kie.smoke.kie.wb.base.methods.RestSmokeIntegrationTestMethods.java

public void urlsGetDeployments(URL deploymentUrl, String user, String password) throws Exception {
    // test with normal RestRequestHelper
    RestRequestHelper requestHelper = getRestRequestHelper(deploymentUrl, user, password);

    ClientRequest restRequest = requestHelper.createRequest("deployment/");
    JaxbDeploymentUnitList depList = get(restRequest, mediaType, 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();
    restRequest = requestHelper.createRequest("deployment/" + deploymentId);
    JaxbDeploymentUnit dep = get(restRequest, mediaType, 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[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
    connection.setRequestMethod("GET");

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

    JaxbSerializationProvider jaxbSerializer = new JaxbSerializationProvider();
    String xmlStrObj = getConnectionContent(connection.getContent());
    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.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java

/**
 * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the given service URL. Currently supports
 * only HTTP./*w  w w  .j a v a  2 s.c o m*/
 *
 * @param serviceUrl URL of the OCSP endpoint.
 * @param request    an OCSP request object.
 * @return OCSP response encoded in ASN.1 structure.
 * @throws CertificateVerificationException
 *
 */
protected OCSPResp getOCSPResponse(String serviceUrl, OCSPReq request) throws CertificateVerificationException {
    try {
        //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 CertificateVerificationException(
                        "Error getting ocsp response." + "Response code is " + con.getResponseCode());
            }

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

From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

/**
 * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the given service URL. Currently supports
 * only HTTP.//w w  w  . j  a  v a  2s. com
 *
 * @param serviceUrl URL of the OCSP endpoint.
 * @param request    an OCSP request object.
 * @return OCSP response encoded in ASN.1 structure.
 * @throws CertificateVerificationException
 *
 */
protected OCSPResp getOCSPResponce(String serviceUrl, OCSPReq request) throws CertificateVerificationException {

    try {
        //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 CertificateVerificationException(
                        "Error getting ocsp response." + "Response code is " + con.getResponseCode());
            }

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

From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java

/**
 * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the
 * given service URL. Currently supports
 * only HTTP.//from  ww w.j  ava2 s  .  c  om
 * 
 * @param serviceUrl
 *            URL of the OCSP endpoint.
 * @param request
 *            an OCSP request object.
 * @return OCSP response encoded in ASN.1 structure.
 * @throws CertificateVerificationException
 * 
 */
protected OCSPResp getOCSPResponce(String serviceUrl, OCSPReq request) throws CertificateVerificationException {

    try {
        // 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 CertificateVerificationException(
                        "Error getting ocsp response." + "Response code is " + con.getResponseCode());
            }

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

From source file:TimestreamsTests.java

/**
 * Performs HTTP get for a given URL// ww w .j a  v  a2  s  .c om
 * 
 * @param url
 *            is the URL to get
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doGet(URL url) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        Map<String, List<String>> responseHeaderFields = conn.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line;
            do {
                line = buff.readLine();
                System.out.println(line + "\n");
            } while (line != null);
        }
        return responseHeaderFields;
    } catch (IOException e) {
        fail = e.getLocalizedMessage();
        return null;
    }
}

From source file:org.fao.geonet.kernel.harvest.harvester.thredds.Harvester.java

/**
 * Get a String result from an HTTP URL/*  w w w.j  av a 2s  .  c  o m*/
 *
 * @param href the URL to get the info from
 **/

private String getResultFromHttpUrl(String href) {
    String result = null;
    try {
        //--- get the version from the OPeNDAP server
        URL url = new URL(href);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        Object o = conn.getContent();
        if (log.isDebugEnabled())
            log.debug("Opened " + href + " and got class " + o.getClass().getName());
        StringBuffer version = new StringBuffer();
        String inputLine;
        BufferedReader dis = null;
        InputStreamReader isr = null;
        InputStream is = null;
        try {
            is = conn.getInputStream();
            isr = new InputStreamReader(is, Constants.ENCODING);
            dis = new BufferedReader(isr);
            while ((inputLine = dis.readLine()) != null) {
                version.append(inputLine + "\n");
            }
            result = version.toString();
            if (log.isDebugEnabled())
                log.debug("Read from URL:\n" + result);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(dis);
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Caught exception " + e + " whilst attempting to query URL " + href);
        e.printStackTrace();
    }
    return result;
}

From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

/**
 * Envia los datos de la peticin OCSP y retorna la respuesta.
 * /*from  ww w. j  a  v  a  2 s. com*/
 * @param url
 *            url del servicio OCSP
 * @param byteRequest
 *            Datos
 * @return respuesta OCSP
 * @throws ExcepcionErrorInterno
 *             No se puede enviar la peticin o recuperar la respuest
 */
private InputStream sendRequest(String url, byte[] byteRequest) throws ExcepcionErrorInterno {
    try {
        HttpURLConnection con = null;
        URL urlOCSP;

        urlOCSP = new URL(url);

        // Establecemos la conexin
        con = (HttpURLConnection) urlOCSP.openConnection();
        // Enviamos las cabeceras
        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));
        // Escribo el request
        dataOut.write(byteRequest);
        // Enviamos y cerramos el envio
        dataOut.flush();
        dataOut.close();

        // Chequeo la respuesta
        if (con.getResponseCode() / 100 != 2) {
            throw new ExcepcionErrorInterno(CodigoError.ERROR_OCSP_NO_DISPONIBLE,
                    con.getResponseMessage() + ",Cdigo: " + con.getResponseCode());
        }

        // Obtengo la respuesta del servidor OCSP
        InputStream in = (InputStream) con.getContent();
        return in;
    } catch (MalformedURLException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_OCSP_URL, e);

    } catch (IOException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_OCSP_IO, e);
    }
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;/*from   w  w w.j  a  v  a  2 s .co m*/
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}