Example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects

List of usage examples for org.apache.commons.httpclient HttpMethod setFollowRedirects

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects.

Prototype

public abstract void setFollowRedirects(boolean paramBoolean);

Source Link

Usage

From source file:org.soaplab.gowlab.GowlabJob.java

/**************************************************************************
 * Create an appropriate HTTP method (as defined in service
 * metadata) an return it.//from   ww  w  .ja v a  2s. c  om
 *
 * A sub-class can overwrite it if it wishes to set some specific
 * HTTP parameters to this method. For example:
 *
 *<pre>
 * HttpMethod method = super.getHttpMethod();
 * method.getParams().setParameter (HttpMethodParams.RETRY_HANDLER, 
 *                                  new DefaultHttpMethodRetryHandler (3, false));
 * return method;
 *</pre>
 *
 **************************************************************************/
protected HttpMethod getHttpMethod() throws SoaplabException {

    // find the URL where to fetch data from
    String supplier = Config.getString(Config.PROP_SUPPLIER,
            metadataAccessor.getAnalysisDef().get(SoaplabConstants.ANALYSIS_SUPPLIER), getServiceName(), this);

    // which HTTP method to use
    String launcherMethod = MetadataUtils.parseLauncher(metadataAccessor, getServiceName(), this)[0];
    if (StringUtils.isNotEmpty(launcherMethod)) {

        String l = launcherMethod.toLowerCase();
        if (l.equals(METHOD_GET)) {
            if (isMultipartUsed()) {
                internalError("Launcher requires a GET method. But it is not compatible with uploading data.");
            }
            return new GetMethod(supplier);
        }
        if (l.equals(METHOD_POST))
            return new PostMethod(supplier);
        if (l.equals(METHOD_HEAD)) {
            if (isMultipartUsed()) {
                internalError("Launcher requires a HEAD method. But it is not compatible with uploading data.");
            }
            return new HeadMethod(supplier);
        }

        internalError("Unknown launcher method '" + launcherMethod + "'.");
    }

    // default behaviour
    HttpMethod method;
    if (isMultipartUsed()) {
        method = new PostMethod(supplier);
    } else {
        method = new GetMethod(supplier);
        method.setFollowRedirects(true);
    }
    return method;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

/**
 * Execute method. In case of any exception thrown by HttpClient, it will release the connection. In other cases it
 * is the duty of caller to do it, or process the input stream.
 * // w  ww .j av a 2  s.com
 * @param method the method
 * @return the int
 */
protected int doExecuteMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    URI methodURI = null;

    try {
        methodURI = method.getURI();
    } catch (URIException e) {
        getLogger().debug("Could not format debug log message", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Invoking HTTP " + method.getName() + " method against remote location " + methodURI);
    }

    RemoteStorageContext ctx = getRemoteStorageContext(repository);

    HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT);

    HostConfiguration httpConfiguration = (HostConfiguration) ctx.getContextObject(CTX_KEY_HTTP_CONFIGURATION);

    method.setRequestHeader(new Header("user-agent", formatUserAgentString(ctx, repository)));
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));

    // HTTP keep alive should not be used, except when NTLM is used
    Boolean isNtlmUsed = (Boolean) ctx.getContextObject(HttpClientProxyUtil.NTLM_IS_IN_USE_KEY);

    if (isNtlmUsed == null || !isNtlmUsed) {
        method.setRequestHeader(new Header("Connection", "close"));
        method.setRequestHeader(new Header("Proxy-Connection", "close"));
    }

    method.setFollowRedirects(true);

    if (StringUtils.isNotBlank(ctx.getRemoteConnectionSettings().getQueryString())) {
        method.setQueryString(ctx.getRemoteConnectionSettings().getQueryString());
    }

    int resultCode;

    try {
        resultCode = httpClient.executeMethod(httpConfiguration, method);

        final Header httpServerHeader = method.getResponseHeader("server");
        checkForRemotePeerAmazonS3Storage(repository,
                httpServerHeader == null ? null : httpServerHeader.getValue());

        Header proxyReturnedErrorHeader = method.getResponseHeader(NEXUS_MISSING_ARTIFACT_HEADER);
        boolean proxyReturnedError = proxyReturnedErrorHeader != null
                && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

        if (resultCode == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteAccessDeniedException(repository, remoteUrl,
                    HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
        } else if (resultCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new RemoteAuthenticationNeededException(repository,
                    HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
        } else if (resultCode == HttpStatus.SC_OK && proxyReturnedError) {
            throw new RemoteStorageException(
                    "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
        }
    } catch (RemoteStorageException e) {
        method.releaseConnection();

        throw e;
    } catch (HttpException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Protocol error while executing " + method.getName()
                + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    } catch (IOException ex) {
        method.releaseConnection();

        throw new RemoteStorageException("Transport error while executing " + method.getName()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex);
    }

    return resultCode;
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;//ww  w. ja  va2 s. c om
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod putMethod = new PutMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        putMethod.setRequestEntity(inputStreamRequestEntity);
        method = putMethod;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod();
    } else {
        log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    Enumeration e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            Enumeration values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = (String) values.nextElement();
                log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    if (log.isInfoEnabled())
        log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java

private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) {
    logger.finest("Fetching content using HttpClient....user-Id: " + tokenId);
    HttpClient hc = new HttpClient();
    hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    HttpMethod method = new GetMethod(href);
    method.addRequestHeader("xx-wings-user-id", tokenId);
    ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>();
    Set<String> keys = requestParameters.keySet();
    for (String key : keys) {
        String value = requestParameters.get(key);
        nvpList.add(new NameValuePair(key, value));
    }// w ww.  j av  a 2s.  co m

    String qs = method.getQueryString();
    if (qs != null) {
        String[] nvPairs = qs.split("&");
        for (String nvPair : nvPairs) {
            String[] mapping = nvPair.split("=");
            nvpList.add(new NameValuePair(mapping[0], mapping[1]));
        }
    }
    method.setFollowRedirects(true);

    NameValuePair[] nvps = new NameValuePair[nvpList.size()];
    nvps = nvpList.toArray(nvps);
    method.setQueryString(nvps);

    byte[] content = null;
    Header[] headers = null;
    try {
        hc.executeMethod(method);
        content = method.getResponseBody();
        headers = method.getResponseHeaders();
    } catch (HttpException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
    return new Response(content, headers);
}

From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java

private InputStream getContentStream(String href) {
    logger.finest("Fetching content using HttpClient....");
    HttpClient hc = new HttpClient();
    hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    HttpMethod method = new GetMethod(href);
    method.setFollowRedirects(true);

    InputStream responseStream = null;
    try {//  ww  w  .  j  av a  2 s  .c o m
        hc.executeMethod(method);
        responseStream = method.getResponseBodyAsStream();
    } catch (HttpException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
    return responseStream;
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java

/**
 * Used by jsFunction_executeMethod().//ww w  .  ja  va 2  s  . c  o  m
 * 
 * @param httpClient
 * @param contentType
 * @param charset
 * @param methodName
 * @param content
 * @param params
 */
private static void setParams(PooledHttpClientHostObject httpClient, HttpMethod method, String contentType,
        String charset, String methodName, Object content, NativeObject params) {
    // other parameters have been set, they are properly set to the
    // corresponding context
    if (ScriptableObject.getProperty(params, "cookiePolicy") instanceof String) {
        method.getParams().setCookiePolicy((String) ScriptableObject.getProperty(params, "cookiePolicy"));
    } else if (!ScriptableObject.getProperty(params, "cookiePolicy").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "contentType") instanceof String) {
        contentType = (String) ScriptableObject.getProperty(params, "contentType");
    } else if (!ScriptableObject.getProperty(params, "contentType").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "charset") instanceof String) {
        charset = (String) ScriptableObject.getProperty(params, "charset");
    } else if (!ScriptableObject.getProperty(params, "charset").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "timeout") instanceof Integer) {
        method.getParams().setSoTimeout((Integer) ScriptableObject.getProperty(params, "timeout"));
    } else if (!ScriptableObject.getProperty(params, "timeout").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "doAuthentication") instanceof Boolean) {
        method.setDoAuthentication((Boolean) ScriptableObject.getProperty(params, "doAuthentication"));
    } else if (!ScriptableObject.getProperty(params, "doAuthentication").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (ScriptableObject.getProperty(params, "followRedirect") instanceof Boolean) {
        method.setFollowRedirects((Boolean) ScriptableObject.getProperty(params, "followRedirect"));
    } else if (!ScriptableObject.getProperty(params, "followRedirect").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }

    if (methodName.equals("POST")) {
        // several parameters are specific to POST method
        if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) {
            boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked");
            ((PostMethod) method).setContentChunked(chuncked);
            if (chuncked && content != null) {
                // if contentChucked is set true, then
                // InputStreamRequestEntity or
                // MultipartRequestEntity is used
                if (content instanceof String) {
                    // InputStreamRequestEntity for string content
                    ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(((String) content).getBytes())));
                } else {
                    // MultipartRequestEntity for Name-Value pair
                    // content
                    NativeObject element;
                    List<StringPart> parts = new ArrayList<StringPart>();
                    String eName;
                    String eValue;
                    // create pairs using name-value pairs
                    for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                        if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                            element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                            if (ScriptableObject.getProperty(element, "name") instanceof String
                                    && ScriptableObject.getProperty(element, "value") instanceof String) {
                                eName = (String) ScriptableObject.getProperty(element, "name");
                                eValue = (String) ScriptableObject.getProperty(element, "value");
                                parts.add(new StringPart(eName, eValue));
                            } else {
                                throw new RuntimeException("Invalid content definition, objects of the content"
                                        + " array should consists with strings for both key/value");
                            }

                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, content array should contain "
                                            + "Javascript Objects");
                        }
                    }
                    ((PostMethod) method).setRequestEntity(new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), method.getParams()));
                }
            }

        } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)
                && content != null) {
            // contentChunking has not used
            if (content instanceof String) {
                try {
                    ((PostMethod) method)
                            .setRequestEntity(new StringRequestEntity((String) content, contentType, charset));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("Unsupported Charset");
                }
            } else {
                NativeObject element;
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                String eName;
                String eValue;
                // create pairs using name-value pairs
                for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                    if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                        element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                        if (ScriptableObject.getProperty(element, "name") instanceof String
                                && ScriptableObject.getProperty(element, "value") instanceof String) {
                            eName = (String) ScriptableObject.getProperty(element, "name");
                            eValue = (String) ScriptableObject.getProperty(element, "value");
                            pairs.add(new NameValuePair(eName, eValue));
                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, objects of the content array "
                                            + "should consists with strings for both key/value");
                        }

                    } else {
                        throw new RuntimeException("Invalid content definition, content array should contain "
                                + "Javascript Objects");
                    }
                }
                ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()]));
            }
        } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) {
            throw new RuntimeException("Method parameters should be Strings");
        }

    } else if (methodName.equals("GET")) {
        // here, the method now is GET
        if (content != null) {
            if (content instanceof String) {
                method.setQueryString((String) content);
            } else {
                NativeObject element;
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                String eName;
                String eValue;
                // create pairs using name-value pairs
                for (int i = 0; i < ((NativeArray) content).getLength(); i++) {
                    if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) {
                        element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content);
                        if (ScriptableObject.getProperty(element, "name") instanceof String
                                && ScriptableObject.getProperty(element, "value") instanceof String) {
                            eName = (String) ScriptableObject.getProperty(element, "name");
                            eValue = (String) ScriptableObject.getProperty(element, "value");
                            pairs.add(new NameValuePair(eName, eValue));
                        } else {
                            throw new RuntimeException(
                                    "Invalid content definition, objects of the content array "
                                            + "should consists with strings for both key/value");
                        }

                    } else {
                        throw new RuntimeException("Invalid content definition, content array should contain "
                                + "Javascript Objects");
                    }
                }
                method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()]));
            }
        }
    } else if (methodName.equals("PUT")) {
        // several parameters are specific to PUT method
        if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) {
            boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked");
            ((PutMethod) method).setContentChunked(chuncked);
            if (chuncked && content != null) {
                // if contentChucked is set true, then
                // InputStreamRequestEntity or
                // MultipartRequestEntity is used
                if (content instanceof String) {
                    // InputStreamRequestEntity for string content
                    ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(((String) content).getBytes())));
                } else {
                    throw new RuntimeException(
                            "Invalid content definition, content should be a string when PUT "
                                    + "method is used");
                }
            }

        } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)
                && content != null) {
            // contentChunking has not used
            if (content instanceof String) {
                try {
                    ((PostMethod) method)
                            .setRequestEntity(new StringRequestEntity((String) content, contentType, charset));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("Unsupported Charset");
                }
            } else {
                throw new RuntimeException(
                        "Invalid content definition, content should be a string when PUT " + "method is used");
            }
        } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) {
            throw new RuntimeException("Method parameters should be Strings");
        }

    }

    // check whether preemptive authentication is used
    if (ScriptableObject.getProperty(params, "preemptiveAuth") instanceof Boolean) {
        httpClient.httpClient.getParams()
                .setAuthenticationPreemptive((Boolean) ScriptableObject.getProperty(params, "preemptiveAuth"));
    } else if (!ScriptableObject.getProperty(params, "preemptiveAuth").equals(UniqueTag.NOT_FOUND)) {
        throw new RuntimeException("Method parameters should be Strings");
    }
}

From source file:org.xwiki.xwoot.manager.internal.DefaultXWootManager.java

private String call(String service) {
    String xwootAppAddress = getXWootAppAddress();

    HttpMethod method = new GetMethod(xwootAppAddress + service);

    /* This is needed because the xwootApp servlet might send redirects to perform initializations */
    method.setFollowRedirects(true);

    try {/*from w w w . j  a v  a 2  s. c o  m*/
        getLogger().debug("Requesting: " + method.getURI());
        if (client.executeMethod(method) < 400) {
            String result = method.getResponseBodyAsString();
            getLogger().debug("Result: " + result);
            return result;
        }
        getLogger().info("Failed call: " + method.getStatusLine());
    } catch (CircularRedirectException e) {
        /*
         * Ignore. This could be normal. For example in the case of connecting/disconnecting the P2P network we call
         * the synchronize servlet that redirects to the boostrap that redirects to synchronize again, causing this
         * exception.
         */
    } catch (Exception ex) {
        getLogger().warn("Exception occured while calling [" + service + "] on [" + xwootAppAddress + "]", ex);
    } finally {
        // Release the connection, since HTTPClient reuses connections for improved performance
        method.releaseConnection();
    }
    return "failed";
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

public static String getResponseBodyAsStringBasedOnProxyAuthOption(String request) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    if (!mytest)/*from   ww w.  j av  a  2 s  .  c  o m*/
        org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final HttpMethod method = new GetMethod(request);
    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (true/*!mytest&&jStockOptions.isProxyAuthEnabled()*/) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.yccheok.jstock.gui.Utils.java

private static String _getResponseBodyAsStringBasedOnProxyAuthOption(HttpClient client, String request) {
    org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(client);
    org.yccheok.jstock.gui.Utils.setHttpClientProxyCredentialsFromJStockOptions(client);

    final HttpMethod method = new GetMethod(request);
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    String respond = null;//from   www  . java  2s.  c o  m
    try {
        if (jStockOptions.isProxyAuthEnabled()) {
            method.setFollowRedirects(false);
            client.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    client.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            client.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.CloudMetadataScanner.java

void sendMessageWithCustomHostHeader(HttpMessage message, String host) throws IOException {
    HttpMethodParams params = new HttpMethodParams();
    params.setVirtualHost(host);//from  w w w .j av  a 2s.  c o m
    HttpMethod method = createRequestMethod(message.getRequestHeader(), message.getRequestBody(), params);
    if (!(method instanceof EntityEnclosingMethod) || method instanceof ZapGetMethod) {
        method.setFollowRedirects(false);
    }
    User forceUser = getParent().getHttpSender().getUser(message);
    message.setTimeSentMillis(System.currentTimeMillis());
    if (forceUser != null) {
        getParent().getHttpSender().executeMethod(method, forceUser.getCorrespondingHttpState());
    } else {
        getParent().getHttpSender().executeMethod(method, null);
    }
    message.setTimeElapsedMillis((int) (System.currentTimeMillis() - message.getTimeSentMillis()));

    HttpMethodHelper.updateHttpRequestHeaderSent(message.getRequestHeader(), method);

    HttpResponseHeader resHeader = HttpMethodHelper.getHttpResponseHeader(method);
    resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null);
    message.setResponseHeader(resHeader);
    message.getResponseBody().setCharset(resHeader.getCharset());
    message.getResponseBody().setLength(0);
    message.getResponseBody().append(method.getResponseBody());
    message.setResponseFromTargetHost(true);
    getParent().notifyNewMessage(this, message);
}