Example usage for org.apache.commons.httpclient HttpException getMessage

List of usage examples for org.apache.commons.httpclient HttpException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.jahia.services.notification.HttpClientService.java

/**
 * Executes a request with GET method to the specified URL and reads the response content as a string.
 *
 * @param url a URL to connect to/*  www  . j a  v  a  2  s . c  o m*/
 * @param headers request headers to be set for connection; <code>null</code> if no additional headers needs to be set
 * @return the string representation of the URL connection response
 * @throws {@link IllegalArgumentException} in case of a malformed URL
 */
public String executeGet(String url, Map<String, String> headers) throws IllegalArgumentException {
    if (StringUtils.isEmpty(url)) {
        throw new IllegalArgumentException("Provided URL is null");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Asked to get content from the URL {} using GET method", url);
    }

    String content = null;

    GetMethod httpMethod = new GetMethod(url);
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpMethod.addRequestHeader(header.getKey(), header.getValue());
        }
    }
    try {
        getHttpClient(url).executeMethod(httpMethod);
        StatusLine statusLine = httpMethod.getStatusLine();

        if (statusLine != null && statusLine.getStatusCode() == SC_OK) {
            content = httpMethod.getResponseBodyAsString();
        } else {
            logger.warn("Connection to URL: " + url + " failed with status " + statusLine);
        }

    } catch (HttpException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } finally {
        httpMethod.releaseConnection();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved " + (content != null ? content.length() : 0) + " characters as a response");
        if (logger.isTraceEnabled()) {
            logger.trace("Content:\n" + content);
        }
    }

    return content;
}

From source file:org.jahia.services.notification.HttpClientService.java

/**
 * Executes a request with POST method to the specified URL and reads the response content as a string.
 *
 * @param url a URL to connect to/*from   w w  w.  j ava2s .c o m*/
 * @param parameters the request parameter to submit; <code>null</code> if no parameters are passed
 * @param headers request headers to be set for connection; <code>null</code> if no additional headers needs to be set
 * @param state the HTTP state object if additional state options, e.g. credentials, needs to be specified; otherwise can be <code>null</code>
 * @return the string representation of the URL connection response
 * @throws {@link IllegalArgumentException} in case of a malformed URL
 */
public String executePost(String url, Map<String, String> parameters, Map<String, String> headers,
        HttpState state) throws IllegalArgumentException {
    if (StringUtils.isEmpty(url)) {
        throw new IllegalArgumentException("Provided URL is null");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Asked to get content from the URL {} using POST method with parameters {}", url,
                parameters);
    }

    String content = null;

    PostMethod httpMethod = new PostMethod(url);
    if (parameters != null && !parameters.isEmpty()) {
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            httpMethod.addParameter(param.getKey(), param.getValue());
        }
    }
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpMethod.addRequestHeader(header.getKey(), header.getValue());
        }
    }

    try {
        getHttpClient(url).executeMethod(null, httpMethod, state);
        StatusLine statusLine = httpMethod.getStatusLine();

        if (statusLine != null && statusLine.getStatusCode() == SC_OK) {
            content = httpMethod.getResponseBodyAsString();
        } else {
            logger.warn("Connection to URL: " + url + " failed with status " + statusLine);
        }

    } catch (HttpException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } finally {
        httpMethod.releaseConnection();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved " + (content != null ? content.length() : 0) + " characters as a response");
        if (logger.isTraceEnabled()) {
            logger.trace("Content:\n" + content);
        }
    }

    return content;
}

From source file:org.jahia.services.templates.ForgeHelper.java

/**
 * Manage Private App Store/*from  w  ww. j a va  2  s.  c o m*/
 */
String createForgeModule(ModuleReleaseInfo releaseInfo, File jar) throws IOException {

    String moduleUrl = null;
    final String url = releaseInfo.getForgeUrl();
    HttpClient client = httpClientService.getHttpClient(url);
    // Get token from Private App Store home page
    GetMethod getMethod = new GetMethod(url + "/home.html");
    getMethod.addRequestHeader("Authorization",
            "Basic " + Base64.encode((releaseInfo.getUsername() + ":" + releaseInfo.getPassword()).getBytes()));
    String token = "";
    try {
        client.executeMethod(getMethod);
        Source source = new Source(getMethod.getResponseBodyAsString());
        if (source.getFirstElementByClass("file_upload") != null) {
            List<net.htmlparser.jericho.Element> els = source.getFirstElementByClass("file_upload")
                    .getAllElements("input");
            for (net.htmlparser.jericho.Element el : els) {
                if (StringUtils.equals(el.getAttributeValue("name"), "form-token")) {
                    token = el.getAttributeValue("value");
                }
            }
        } else {
            throw new IOException(
                    "Unable to get Private App Store site information, please check your credentials");
        }
    } finally {
        getMethod.releaseConnection();
    }
    Part[] parts = { new StringPart("form-token", token), new FilePart("file", jar) };

    // send module
    PostMethod postMethod = new PostMethod(url + "/contents/modules-repository.createModuleFromJar.do");
    postMethod.getParams().setSoTimeout(0);
    postMethod.addRequestHeader("Authorization",
            "Basic " + Base64.encode((releaseInfo.getUsername() + ":" + releaseInfo.getPassword()).getBytes()));
    postMethod.addRequestHeader("accept", "application/json");
    postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
    String result = null;
    try {
        client.executeMethod(null, postMethod);
        StatusLine statusLine = postMethod.getStatusLine();

        if (statusLine != null && statusLine.getStatusCode() == SC_OK) {
            result = postMethod.getResponseBodyAsString();
        } else {
            logger.warn("Connection to URL: " + url + " failed with status " + statusLine);
        }

    } catch (HttpException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
    } finally {
        postMethod.releaseConnection();
    }

    if (StringUtils.isNotEmpty(result)) {
        try {
            JSONObject json = new JSONObject(result);
            if (!json.isNull("moduleAbsoluteUrl")) {
                moduleUrl = json.getString("moduleAbsoluteUrl");
            } else if (!json.isNull("error")) {
                throw new IOException(json.getString("error"));
            } else {
                logger.warn("Cannot find 'moduleAbsoluteUrl' entry in the create module actin response: {}",
                        result);
                throw new IOException("unknown");
            }
        } catch (JSONException e) {
            logger.error("Unable to parse the response of the module creation action. Cause: " + e.getMessage(),
                    e);
        }
    }

    return moduleUrl;
}

From source file:org.jboss.net.protocol.http.DavURLLister.java

public Collection listMembers(URL baseUrl, URLFilter filter, boolean scanNonDottedSubDirs) throws IOException {
    WebdavResource resource = null;//from ww w .j  a  v  a 2 s  .  c  o m
    try {
        resource = new WebdavResource(baseUrl.toString());
        WebdavResource[] resources = resource.listWebdavResources();
        List urls = new ArrayList(resources.length);
        for (int i = 0; i < resources.length; i++) {
            WebdavResource member = resources[i];
            HttpURL httpURL = member.getHttpURL();
            if (filter.accept(baseUrl, httpURL.getName())) {
                String url = httpURL.getUnescapedHttpURL();
                if (member.isCollection()) {
                    if (!url.endsWith("/"))
                        url += "/";

                    // it is a directory: do we have to recursively list its content?
                    //
                    if (scanNonDottedSubDirs && getFilePartFromUrl(httpURL.toURL()).indexOf(".") == -1) {
                        URL subUrl = new URL(url);
                        urls.addAll(listMembers(subUrl, filter, scanNonDottedSubDirs));
                    } else {
                        urls.add(new URL(url));
                    }
                } else {
                    urls.add(new URL(url));
                }

            }
        }
        return urls;
    } catch (HttpException e) {
        throw new IOException(e.getMessage());
    } catch (MalformedURLException e) {
        // should not happen
        throw new IllegalStateException(e.getMessage());
    } finally {
        if (resource != null) {
            resource.close();
        }
    }
}

From source file:org.jboss.remoting.transport.http.HTTPServerInvoker.java

private boolean checkForConnecctionClose(Header[] headers) {
    boolean keepAlive = true;

    if (headers != null) {
        for (int x = 0; x < headers.length; x++) {
            String name = headers[x].getName();
            if ("Connection".equals(name)) {
                String value = headers[x].getValue();
                if (value != null) {
                    if ("close".equalsIgnoreCase(value)) {
                        keepAlive = false;
                        break;
                    }//from w w w. j  a  v  a  2s .  c  om
                } else {
                    try {
                        HeaderElement[] hdrElements = headers[x].getValues();
                        if (hdrElements != null) {
                            for (int i = 0; i < hdrElements.length; i++) {
                                NameValuePair pair = hdrElements[i].getParameterByName("Connection");
                                if ("close".equalsIgnoreCase(pair.getValue())) {
                                    keepAlive = false;
                                    break;
                                }
                            }
                        }
                    } catch (HttpException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
    }

    return keepAlive;
}

From source file:org.kepler.actor.rest.RESTService.java

/**
 *
 * @param pmPairList/*www  . ja v  a2s .co  m*/
 *            List of the name and value parameters that user has provided
 *            through paramInputPort. However in method this list is
 *            combined with the user configured ports and the combined list
 *            name value pair parameters are added to the service URL
 *            separated by ampersand.
 * @param nvPairList
 *            List of the name and value parameters that user has provided
 * @return the results after executing the Get service.
 */
public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL)
        throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN GET METHOD");
    }
    //log.debug("I AM IN GET METHOD");

    HttpClient client = new HttpClient();

    StringBuilder results = new StringBuilder();
    results.append(serSiteURL);
    List<NameValuePair> fullPairList = getCombinedPairList(nvPairList);

    if (fullPairList.size() > 0) {

        results.append("?");

        int pairListSize = fullPairList.size();
        for (int j = 0; j < pairListSize; j++) {
            NameValuePair nvPair = fullPairList.get(j);
            results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue());
            if (j < pairListSize - 1) {
                results.append("&");
            }

        }
    }
    if (_debugging) {
        _debug("RESULTS :" + results.toString());
    }

    // Create a method instance.
    GetMethod method = new GetMethod(results.toString());
    InputStream rstream = null;
    StringBuilder resultsForDisplay = new StringBuilder();

    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excuteGetMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug(messageBldr.toString());
        if (_debugging) {
            _debug(messageBldr.toString());
        }

        // if(statusCode == 201){
        // System.out.println("Success -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }else{
        // System.out.println("Failure -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }

        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

        String s;
        while ((s = br.readLine()) != null) {
            resultsForDisplay.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException httpe) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + httpe.getMessage());
        }
        httpe.printStackTrace();
        throw new IllegalActionException(this, httpe, "Fatal Protocol Violation: " + httpe.getMessage());
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
        }
        conExp.printStackTrace();
        throw new IllegalActionException(this, conExp,
                "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("IOException: " + ioe.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        ioe.printStackTrace();
        throw new IllegalActionException(this, ioe, "IOException: " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Fatal transport error: " + e.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw new IllegalActionException(this, e, "Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
        client = null;
        // close InputStream;
        if (rstream != null)
            try {
                rstream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage());
            }
    }

    return resultsForDisplay.toString();

}

From source file:org.kepler.actor.rest.RESTService.java

/**
 * File & regular parameters are passed as two separate lists and they are
 * treated little differently. If flPairList is not null or empty then this
 * method uses Part Object else no.//from   ww w  .j  a  v a2s  .co m
 *
 * @param pmPairList
 *            List of the name and value parameters that user has provided
 * @param flPairList
 *            List of the name and value (full file path)of file parameters.
 *            It is essentially a list of files that user wishes to attach.
 * @return the results after executing the Post service.
 */
public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList,
        String serSiteURL) throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN POST METHOD");
    }

    //log.debug("I AM IN POST METHOD");
    String postAddress = serSiteURL;

    HttpClient client = new HttpClient();
    MultipartPostMethod method = new MultipartPostMethod(postAddress);
    List<NameValuePair> fullNameValueList = getCombinedPairList(pmPairList);
    if (flPairList != null && flPairList.size() > 0) {
        fullNameValueList.addAll(flPairList);
        int totalSize = fullNameValueList.size();
        Part[] parts = new Part[totalSize];

        try {

            for (int i = 0; i < parts.length; i++) {

                String nm = fullNameValueList.get(i).getName();
                String vl = fullNameValueList.get(i).getValue();

                if (i > totalSize - flPairList.size() - 1) {
                    System.out.println("FILE NAME: " + nm);
                    File file = getFileObject(vl);
                    // System.out.println("FILE NAME: " + file.getName());
                    parts[i] = new FilePart(nm, file);
                    method.addPart(parts[i]);
                    System.out.println("PARTS: " + i + " " + parts[i].getName());
                    System.out.println("file Name: " + vl);

                } else {

                    System.out.println("PARAMETER NAME: " + nm);
                    System.out.println("PARAMETER Value: " + vl);
                    parts[i] = new StringPart(nm, vl);
                    method.addPart(parts[i]);

                }
                if (_debugging) {
                    _debug("Value of i: " + i);
                }

            }

        } catch (FileNotFoundException fnfe) {
            if (_debugging) {
                _debug("File Not Exception: " + fnfe.getMessage());
            }
            fnfe.printStackTrace();
            throw new IllegalActionException(this, fnfe, "File Not Found: " + fnfe.getMessage());
        }
    } else {
        for (NameValuePair nmPair : fullNameValueList) {
            method.addParameter(nmPair.getName(), nmPair.getValue());
        }
    }

    InputStream rstream = null;
    StringBuilder results = new StringBuilder();
    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

        // if(statusCode == 201){
        // System.out.println("Succuess -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }else{
        // System.out.println("Failure -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }
        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

        log.debug("BEFORE WHILE LOOP");
        String s;
        while ((s = br.readLine()) != null) {
            results.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException e) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + e.getMessage());
        }
        e.printStackTrace();
        return "Protocol Violation";
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
        }
        conExp.printStackTrace();
        throw new IllegalActionException(this, conExp,
                "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        ioe.printStackTrace();
        throw new IllegalActionException(this, ioe, "IOException: Perhaps could not"
                + " connect to the service '" + serSiteURL + "'. " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Error: " + e.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw new IllegalActionException(this, e, "Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
        client = null;
        // close InputStream;
        if (rstream != null)
            try {
                rstream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage());
            }
    }
    return results.toString();
}

From source file:org.manalang.monkeygrease.Config.java

public synchronized void load() {

    InputStream is = null;/*from   ww  w.j a  v  a 2 s  .co  m*/
    GetMethod method = null;

    if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null) {
        method = new GetMethod(MonkeygreaseFilter.remoteConfigURL);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            // Execute the method.
            int statusCode = MonkeygreaseFilter.client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                MonkeygreaseFilter.log.severe("Method failed: " + method.getStatusLine());
            }
            is = method.getResponseBodyAsStream();
        } catch (HttpException e) {
            MonkeygreaseFilter.log.severe("Fatal protocol violation: " + e.getMessage());
        } catch (IOException e) {
            MonkeygreaseFilter.log.severe("Fatal transport error: " + e.getMessage());
        }

    } else {
        is = context.getResourceAsStream(DEFAULT_WEB_CONF_FILE);

        if (is == null) {
            System.out.println("unable to find monkeygrease conf file " + DEFAULT_WEB_CONF_FILE);
        }
    }

    DocumentBuilder parser;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // factory.setValidating(true);
    // factory.setNamespaceAware(true);
    // factory.setIgnoringComments(true);
    // factory.setIgnoringElementContentWhitespace(true);
    try {
        parser = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        MonkeygreaseFilter.log.severe("Unable to setup XML parser for reading conf " + e.toString());
        return;
    }

    // parser.setErrorHandler(handler);
    // parser.setEntityResolver(handler);

    try {
        Document doc = parser.parse(is);

        if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null)
            method.releaseConnection();

        NodeList rulesConf = doc.getElementsByTagName("rule");
        rules = new Rules();

        for (int i = 0; i < rulesConf.getLength(); i++) {
            Node ruleNode = rulesConf.item(i);
            Rule rule = new Rule(ruleNode);
            if (rule.isEnabled())
                rules.add(rule);
        }
        // processConfDoc(doc);
    } catch (SAXParseException e) {
        MonkeygreaseFilter.log.severe("Parse error on line " + e.getLineNumber() + " " + e.toString());
    } catch (Exception e) {
        MonkeygreaseFilter.log.severe("Exception loading conf " + " " + e.toString());
    }
}

From source file:org.manalang.monkeygrease.utils.HttpClient.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = request.getParameter("u");
    String method = request.getParameter("m");
    String params = request.getParameter("p");
    InputStream is = null;//from w  w w.  j a va 2  s . c  o m

    if (url == null || url == "")
        return;

    if (method != null && method.toLowerCase().equals("post")) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(url);

        // If params avail, set post data
        if (params != null && params != "") {
            String[] paramArray = params.split("&");
            NameValuePair[] postData = new NameValuePair[paramArray.length];
            for (int i = 0; i < paramArray.length; i++) {
                String[] nameVal = paramArray[i].split("=");
                String name = nameVal[0];
                String value = nameVal[1];
                postData[i] = new NameValuePair(name, value);
            }
            postMethod.setRequestBody(postData);
        }

        // Provide custom retry handler is necessary
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(2, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(postMethod);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + postMethod.getStatusLine());
            }

            // Read the response body.
            is = postMethod.getResponseBodyAsStream();
            Header[] headers = postMethod.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];
                response.setHeader(header.getName(), header.getValue());
            }
            PrintWriter out = response.getWriter();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
            out.close();

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            postMethod.releaseConnection();
        }

    } else {
        if (params != null) {
            if (url.indexOf("?") == -1) {
                url = url + "?" + params;
            } else {
                url = url + "&" + params;
            }
        }

        // Create a method instance.
        GetMethod getMethod = new GetMethod(url);

        // Provide custom retry handler is necessary
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(2, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(getMethod);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + getMethod.getStatusLine());
            }

            // Read the response body.
            is = getMethod.getResponseBodyAsStream();
            Header[] headers = getMethod.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];
                response.setHeader(header.getName(), header.getValue());
            }
            PrintWriter out = response.getWriter();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
            out.close();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not
            // binary data

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            getMethod.releaseConnection();
        }
    }
}

From source file:org.medici.bia.controller.manuscriptviewer.ReverseProxyIIPImageController.java

/**
 * //from   w ww  . ja  va  2  s.com
 * 
 * @param volumeId
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public void proxyIIPImage(HttpServletRequest httpServletRequest, HttpServletResponse response) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();
    String versionServer = ApplicationPropertyManager.getApplicationProperty("iipimage.reverseproxy.version");
    String connectUrl = null;

    if (versionServer.equals("0.9.8")) {
        connectUrl = getConnectUrlServer098(httpServletRequest);
    } else if (versionServer.equals("0.9.9")) {
        connectUrl = getConnectUrlServer099(httpServletRequest);
    }

    // Create a method instance.
    GetMethod method = new GetMethod(connectUrl);

    try {
        // Execute the method.
        client.executeMethod(method);
        logger.debug("Proxying IIPImage Url : " + connectUrl + " (Status Line" + method.getStatusLine() + ")");

        // Set content type 
        response.setContentType(method.getResponseHeader("Content-Type").getValue());
        //response.getOutputStream().write(method.getResponseBody());
        // Redirecting proxed output to client
        IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());

        // Flushing request
        response.getOutputStream().flush();
    } catch (HttpException httpException) {
        logger.error("Fatal protocol violation: " + httpException.getMessage());
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}