Example usage for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream.

Prototype

@Override
public InputStream getResponseBodyAsStream() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as an InputStream .

Usage

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Gets the HTTP response stream./*from   w  ww  .  j a  va 2s .c  om*/
 * @param method the HTTP method
 * @return the response stream
 * @throws IOException if an i/o exception occurs 
 */
private InputStream getResponseStream(HttpMethodBase method) throws IOException {
    // Check is Content-Encoding is gzip
    Header hdr = method.getResponseHeader("Content-Encoding");
    if (hdr != null && "gzip".equals(hdr.getValue())) {
        return new GZIPInputStream(method.getResponseBodyAsStream());
    }
    return method.getResponseBodyAsStream();
}

From source file:fr.openwide.talendalfresco.rest.client.AlfrescoRestClient.java

public void execute(ClientCommand clientCommand) throws RestClientException {

    int statusCode = -1;
    HttpMethodBase method = null;
    try {/* www . j a v a  2 s .  c  o m*/
        // building method (and body entity if any)
        method = clientCommand.createMethod();

        // setting server URL
        method.setURI(new URI(restCommandUrlPrefix + clientCommand.getName(), false));
        method.getParams().setContentCharset(this.restEncoding);

        // building params (adding ticket)
        List<NameValuePair> params = clientCommand.getParams();
        params.add(new NameValuePair(TICKET_PARAM, ticket));
        method.setQueryString(params.toArray(EMPTY_NAME_VALUE_PAIR));

        // Execute the method.
        statusCode = client.executeMethod(method);

        // checking HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new RestClientException("Bad HTTP Status : " + statusCode);
        }

        // parsing response
        XMLEventReader xmlReader = null;
        try {
            xmlReader = XmlHelper.createXMLEventReader(method.getResponseBodyAsStream(), this.restEncoding);

            clientCommand.handleResponse(xmlReader);

            if (!RestConstants.CODE_OK.equals(clientCommand.getResultCode())) {
                //String msg = "Business error in command " + clientCommand.toString();
                //logger.error(msg, e);
                throw new RestClientException(clientCommand.getResultMessage(),
                        new RestClientException(clientCommand.getResultError()));
            }
        } catch (XMLStreamException e) {
            String msg = "XML parsing error on response body : ";
            try {
                msg += new String(method.getResponseBody());
            } catch (IOException ioex) {
                msg += "[unreadable]";
            }
            ;
            //logger.error(msg, e);
            throw new RestClientException(msg, e);
        } catch (IOException e) {
            String msg = "IO Error when parsing XML response body : ";
            //logger.error(msg, e);
            throw new RestClientException(msg, e);

        } finally {
            if (xmlReader != null) {
                try {
                    xmlReader.close();
                } catch (Throwable t) {
                }
            }
        }

    } catch (RestClientException rcex) {
        throw rcex;
    } catch (URIException e) {
        throw new RestClientException("URI error while executing command " + clientCommand, e);
    } catch (HttpException e) {
        throw new RestClientException("HTTP error while executing command " + clientCommand, e);
    } catch (IOException e) {
        throw new RestClientException("IO error while executing command " + clientCommand, e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.comcast.cats.jenkins.service.AbstractService.java

/**
 * Sends Http request to Jenkins server and read the respose.
 * //from  ww  w  .jav  a  2 s .com
 * @param mapperClass
 * @param domainObject
 * @param client
 * @param request
 * @return
 * @throws NumberFormatException
 * @throws IOException
 * @throws HttpException
 * @throws URIException
 */
private Object sendRequestToJenkins(Class<?> mapperClass, Object domainObject, HttpClient client,
        HttpMethodBase request, String apiToken)
        throws NumberFormatException, IOException, HttpException, URIException {
    String passwdord = apiToken;
    if (apiToken.isEmpty()) {
        // Set jenkins password if no API token is present
        passwdord = jenkinsClientProperties.getJenkinsPassword();
    }
    client.getState().setCredentials(
            new AuthScope(jenkinsClientProperties.getJenkinsHost(),
                    new Integer(jenkinsClientProperties.getJenkinsPort()), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(jenkinsClientProperties.getJenkinsUsername(), passwdord));
    if (!apiToken.isEmpty()) {
        client.getParams().setAuthenticationPreemptive(true);
    }

    int responseCode = client.executeMethod(request);

    LOGGER.info("[REQUEST][" + request.getURI().toString() + "]");
    LOGGER.info("[STATUS][" + request.getStatusLine().toString() + "]");

    if (HttpStatus.SC_OK == responseCode) {
        try {
            Serializer serializer = new Persister();
            domainObject = serializer.read(mapperClass, request.getResponseBodyAsStream(), false);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
    return domainObject;
}

From source file:com.owncloud.android.lib.resources.files.ToggleEncryptionOperation.java

/**
 * @param client Client object//from   ww  w.  j av a2s  . c o m
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    HttpMethodBase method = null;

    ReadRemoteFolderOperation remoteFolderOperation = new ReadRemoteFolderOperation(remotePath);
    RemoteOperationResult remoteFolderOperationResult = remoteFolderOperation.execute(client);

    // Abort if not empty
    // Result has always the folder and maybe children, so size == 1 is ok
    if (remoteFolderOperationResult.isSuccess() && remoteFolderOperationResult.getData().size() > 1) {
        return new RemoteOperationResult(false, "Non empty", HttpStatus.SC_FORBIDDEN);
    }

    try {
        String url = client.getBaseUri() + ENCRYPTED_URL + localId;
        if (encryption) {
            method = new PutMethod(url);
        } else {
            method = new DeleteMethod(url);
        }

        // remote request
        method.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        method.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);

        int status = client.executeMethod(method, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            result = new RemoteOperationResult(true, method);
        } else {
            result = new RemoteOperationResult(false, method);
            client.exhaustResponse(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Setting encryption status of " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}

From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * /* w w  w . jav a 2  s .  co  m*/
 * @param uriToCheck
 *            the URL to check (or <code>null</code> if text or file should
 *            be used as input
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (text != null) {
            params.add(new NameValuePair("text", text));
        }
    }
    if (usermedium != null) {
        params.add(new NameValuePair("usermedium", usermedium));
    }
    if (profile != null) {
        params.add(new NameValuePair("profile", profile));
    }
    if (lang != null) {
        params.add(new NameValuePair("lang", lang));
    }
    if (warning != null) {
        params.add(new NameValuePair("warning", warning));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked via traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (text != null) {
            //Text request must be multipart encoded too...
            postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]),
                    postMethod.getParams()));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(
                    Tools.createFileUpload(file, "file", null, params, postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * /*from  w  ww  .ja v a 2  s. com*/
 * @param uriToCheck
 *            the URL to check
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (fragment != null) {
            params.add(new NameValuePair("fragment", fragment));
        }
    }
    if (debug) {
        params.add(new NameValuePair("debug", "1"));
    }
    if (charset != null) {
        params.add(new NameValuePair("charset", charset));
    }
    if (doctype != null) {
        params.add(new NameValuePair("doctype", doctype));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked wia traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (fragment != null) {
            //Fragment request can be checked via FORM Submission
            postMethod.addParameters(params.toArray(new NameValuePair[0]));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(Tools.createFileUpload(uploaded_file, "uploaded_file", charset, params,
                    postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

From source file:net.sf.antcontrib.net.httpclient.AbstractMethodTask.java

public void execute() throws BuildException {
    if (httpClient == null) {
        httpClient = new HttpClient();
    }//from   www.  j ava  2 s.c o m

    HttpMethodBase method = createMethodIfNecessary();
    configureMethod(method);
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCodeProperty != null) {
            Property p = (Property) getProject().createTask("property");
            p.setName(statusCodeProperty);
            p.setValue(String.valueOf(statusCode));
            p.perform();
        }

        Iterator it = responseHeaders.iterator();
        while (it.hasNext()) {
            ResponseHeader header = (ResponseHeader) it.next();
            Property p = (Property) getProject().createTask("property");
            p.setName(header.getProperty());
            Header h = method.getResponseHeader(header.getName());
            if (h != null && h.getValue() != null) {
                p.setValue(h.getValue());
                p.perform();
            }

        }
        if (responseDataProperty != null) {
            Property p = (Property) getProject().createTask("property");
            p.setName(responseDataProperty);
            p.setValue(method.getResponseBodyAsString());
            p.perform();
        } else if (responseDataFile != null) {
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                is = method.getResponseBodyAsStream();
                fos = new FileOutputStream(responseDataFile);
                byte buf[] = new byte[10 * 1024];
                int read = 0;
                while ((read = is.read(buf, 0, 10 * 1024)) != -1) {
                    fos.write(buf, 0, read);
                }
            } finally {
                FileUtils.close(fos);
                FileUtils.close(is);
            }
        }
    } catch (IOException e) {
        throw new BuildException(e);
    } finally {
        cleanupResources(method);
    }
}

From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java

public InputStream executeQuery(String str, OutputFormat fmt, String url,
        List<CompilationUnit.Parameter> params) throws Exception {
    HttpMethodBase method = null;
    if (str.length() + url.length() < MAX_URL_LENGTH) {
        //Use GET for small-ish queries
        method = new GetMethod(url);
        NameValuePair[] parameters = new NameValuePair[params.size() + 1];
        parameters[0] = new NameValuePair("query", str);
        int i = 1;
        for (CompilationUnit.Parameter param : params) {
            parameters[i++] = new NameValuePair(param.getName(), param.getValue());
        }/*from www.jav  a  2 s. c  o  m*/
        method.setQueryString(parameters);
    } else {
        //Use POST for bigger ones to avoid 413 FULL_HEAD
        // QQQ POST API doesn't allow encoding additional parameters
        method = new PostMethod(url);
        ((PostMethod) method).setRequestEntity(new StringRequestEntity(str));
    }

    //Set accepted output response type
    method.setRequestHeader("Accept", fmt.mimeType());
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SPDocument.java

/**
 * For downloading the contents of the documents using its URL. Used with
 * content feeds only./* ww  w  .j  a  v a  2  s. co m*/
 *
 * @return {@link SPContent} containing the status, content type and
 *    content stream.
 * @throws RepositoryException
 */
@VisibleForTesting
SPContent downloadContents() throws RepositoryException {
    InputStream docContentStream = null;
    String docContentType = null;

    if (null == sharepointClientContext) {
        LOGGER.log(Level.SEVERE,
                "Failed to download document content because the connector context is not found!");
        return new SPContent(SPConstants.CONNECTIVITY_FAIL, docContentType, docContentStream);
    }
    LOGGER.config("Document URL [ " + contentDwnldURL + " is getting processed for contents");
    if (isEmptyDocument()) {
        LOGGER.config("Document URL [" + contentDwnldURL + "] is empty document");
        return new SPContent("empty", docContentType, docContentStream);
    }
    int responseCode = 0;
    boolean downloadContent = true;
    if (getFileSize() > 0 && sharepointClientContext.getTraversalContext() != null) {
        if (getFileSize() > sharepointClientContext.getTraversalContext().maxDocumentSize()) {
            // Set the flag to download content to be false so that no
            // content is downloaded as the CM itself will drop it.
            downloadContent = false;
            LOGGER.log(Level.WARNING,
                    "Dropping content of document : " + getUrl() + " with docId : " + docId + " of size "
                            + getFileSize() + " as it exceeds the allowed max document size "
                            + sharepointClientContext.getTraversalContext().maxDocumentSize());
        }
    }
    if (downloadContent) {
        final String docURL = Util.encodeURL(contentDwnldURL);
        final HttpMethodBase method;
        try {
            method = new GetMethod(docURL);
            responseCode = sharepointClientContext.checkConnectivity(docURL, method);
            if (responseCode != 200) {
                LOGGER.warning("Unable to get contents for document '" + getUrl()
                        + "'. Received the response code: " + responseCode);
                return new SPContent(Integer.toString(responseCode), responseCode, docContentType,
                        docContentStream);
            }

            InputStream contentStream = method.getResponseBodyAsStream();
            if (contentStream != null) {
                docContentStream = new FilterInputStream(contentStream) {
                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                        } finally {
                            method.releaseConnection();
                        }
                    }
                };
            }
        } catch (Throwable t) {
            String msg = new StringBuffer("Unable to fetch contents from URL: ").append(url).toString();
            LOGGER.log(Level.WARNING, "Unable to fetch contents from URL: " + url, t);
            throw new RepositoryDocumentException(msg, t);
        }
        // checks if the give URL is for .msg file if true set the mimetype
        // directly to application/vnd.ms-outlook as mimetype returned by the
        // header is incorrect for .msg files
        if (!contentDwnldURL.endsWith(MSG_FILE_EXTENSION)) {
            final Header contentType = method.getResponseHeader(SPConstants.CONTENT_TYPE_HEADER);
            if (contentType != null) {
                docContentType = contentType.getValue();
            } else {
                LOGGER.info("The content type returned for doc : " + toString() + " is : null ");
            }
        } else {
            docContentType = MSG_FILE_MIMETYPE;
        }

        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.fine("The content type for doc : " + toString() + " is : " + docContentType);
        }

        if (sharepointClientContext.getTraversalContext() != null && docContentType != null) {
            // TODO : This is to be revisited later where a better
            // approach to skip documents or only content is
            // available
            int mimeTypeSupport = sharepointClientContext.getTraversalContext()
                    .mimeTypeSupportLevel(docContentType);
            if (mimeTypeSupport == 0) {
                docContentStream = null;
                LOGGER.log(Level.WARNING, "Dropping content of document : " + getUrl() + " with docId : "
                        + docId + " as the mimetype : " + docContentType + " is not supported");
            } else if (mimeTypeSupport < 0) {
                // Since the mimetype is in list of 'ignored' mimetype
                // list, mark it to be skipped from sending
                String msg = new StringBuffer("Skipping the document with docId : ").append(getDocId())
                        .append(" doc URL: ").append(getUrl())
                        .append(" as the mimetype is in the 'ignored' mimetypes list ").toString();
                // Log it to the excluded_url log
                sharepointClientContext.logExcludedURL(msg);
                throw new SkippedDocumentException(msg);
            }
        }
    }

    return new SPContent(SPConstants.CONNECTIVITY_SUCCESS, responseCode, docContentType, docContentStream);
}

From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java

@Override
public SampleResult sample() {
    HttpMethodBase httpMethod = null;
    HttpClient client = null;//w  w  w  . j  ava 2 s.co m
    InputStream instream = null;
    SampleResult res = new SampleResult();
    try {
        res.setSuccessful(false);
        res.setResponseCode("000");
        res.setSampleLabel(getName());
        res.setURL(getUrl());
        res.setDataEncoding("UTF-8");
        res.setDataType("text/xml");
        res.setSamplerData(getRequestBody());
        res.setMonitor(isMonitor());
        res.sampleStart();

        String urlStr = getUrl().toString();
        log.debug("Start : sample " + urlStr);
        log.debug("method " + getMethod());

        httpMethod = createHttpMethod(getMethod(), urlStr);
        setDefaultRequestHeaders(httpMethod);
        client = setupConnection(getUrl(), httpMethod);
        if (httpMethod instanceof EntityEnclosingMethod) {
            ((EntityEnclosingMethod) httpMethod)
                    .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8"));
        }
        overrideHeaders(httpMethod, urlStr, getMethod());
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = -1;
        try {
            statusCode = client.executeMethod(httpMethod);
        } catch (RuntimeException e) {
            log.error("Exception when executing '" + httpMethod + "'", e);
            throw e;
        }

        instream = httpMethod.getResponseBodyAsStream();
        if (instream != null) {

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null) {
            ct = h.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }

        String responseHeaders = getResponseHeaders(httpMethod);
        res.setResponseHeaders(responseHeaders);

        log.debug("End : sample");
        httpMethod.releaseConnection();

        return res;
    } catch (MalformedURLException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } catch (IllegalArgumentException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        log.warn(e.getMessage());
        res.setResponseMessage(e.getMessage());
        return res;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
            return res;
        }
    }
}