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

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

Introduction

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

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a map of
 * properties to populate that template with. An example might be a SOAP call.
 *
 * <pre>/*from   w  w w  .  j a  va2s . c  o  m*/
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 *
 * </pre>
 *
 * @param resource
 *          the resource containing the proxy end point specification.
 * @param headers
 *          a map of headers to set int the request.
 * @param input
 *          a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *          containing the request body (can be null if the call requires no body or the
 *          template will be used to generate the body)
 * @param requestContentLength
 *          if the requestImputStream is specified, the length specifies the lenght of
 *          the body.
 * @param requerstContentType
 *          the content type of the request, if null the node property
 *          sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            if (isUnsafeProxyDefinition(node)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            // Find all velocity replacement variable(s) in the endpointURL,
            // copy any equivalent keys from the input Map, to a new Map that
            // can be process by Velocity. In the new Map, the Map value field
            // has been changed from RequestParameter[] to String.

            Map<String, String> inputContext = new HashMap<String, String>();

            int startPosition = endpointURL.indexOf("${");
            while (startPosition > -1) {
                int endPosition = endpointURL.indexOf("}", startPosition);
                if (endPosition > -1) {
                    String key = endpointURL.substring(startPosition + 2, endPosition);
                    Object value = input.get(key);
                    if (value instanceof RequestParameter[]) {
                        // now change input value object from RequestParameter[] to String
                        // and add to inputContext Map.
                        RequestParameter[] requestParameters = (RequestParameter[]) value;
                        inputContext.put(key, requestParameters[0].getString());
                    } else {
                        // KERN-1346 regression; see KERN-1409
                        inputContext.put(key, String.valueOf(value));
                    }
                    // look for the next velocity replacement variable
                    startPosition = endpointURL.indexOf("${", endPosition);
                } else {
                    break;
                }
            }

            VelocityContext context = new VelocityContext(inputContext);

            // add in the config properties from the bundle overwriting everythign else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString());
                } catch (Exception e) {
                    logger.debug("The Proxy request specified by  " + node + " failed, cause follows:", e);
                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) {
                    long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong();
                    method = new HeadMethod(endpointURL);
                    HttpMethodParams params = new HttpMethodParams(method.getParams());
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    method.setParams(params);
                    method.setFollowRedirects(true);
                    populateMethod(method, node, headers);
                    int result = httpClient.executeMethod(method);
                    if (externalAuthenticatingProxy && result == 407) {
                        method.releaseConnection();
                        method.setDoAuthentication(true);
                        result = httpClient.executeMethod(method);
                    }
                    if (result == 200) {
                        // Check if the content-length is smaller than the maximum (if any).
                        Header contentLengthHeader = method.getResponseHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", method);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(result, method);
                    }
                }
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case HEAD:
                method = new HeadMethod(endpointURL);
                HttpMethodParams params = new HttpMethodParams(method.getParams());
                // make certain we reject the body of a head
                params.setBooleanParameter("http.protocol.reject-head-body", true);
                method.setParams(params);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case OPTIONS:
                method = new OptionsMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case POST:
                method = new PostMethod(endpointURL);
                break;
            case PUT:
                method = new PutMethod(endpointURL);
                break;
            default:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);

            }

            populateMethod(method, node, headers);

            if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof PostMethod) {
                    PostMethod postMethod = (PostMethod) method;
                    ArrayList<Part> parts = new ArrayList<Part>();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof RequestParameter[]) {
                            for (RequestParameter val : (RequestParameter[]) param.getValue()) {
                                Part part = null;
                                if (val.isFormField()) {
                                    part = new StringPart(param.getKey(), val.getString());
                                } else {
                                    ByteArrayPartSource source = new ByteArrayPartSource(key, val.get());
                                    part = new FilePart(key, source);
                                }
                                parts.add(part);
                            }
                        } else {
                            parts.add(new StringPart(key, value.toString()));
                        }
                        Part[] partsArray = parts.toArray(new Part[parts.size()]);
                        postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
                    }
                }
            } else {

                if (method instanceof EntityEnclosingMethod) {
                    String contentType = requestContentType;
                    if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) {
                        contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString();

                    }
                    if (contentType == null) {
                        contentType = APPLICATION_OCTET_STREAM;
                    }
                    EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method;
                    if (requestInputStream != null) {
                        eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream,
                                requestContentLength, contentType));
                    } else {
                        // build the request
                        Template template = velocityEngine.getTemplate(node.getPath());
                        StringWriter body = new StringWriter();
                        template.merge(context, body);
                        byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                        eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType));

                    }
                }
            }

            int result = httpClient.executeMethod(method);
            if (externalAuthenticatingProxy && result == 407) {
                method.releaseConnection();
                method.setDoAuthentication(true);
                result = httpClient.executeMethod(method);
            }
            if (result == 302 && method instanceof EntityEnclosingMethod) {
                // handle redirects on post and put
                String url = method.getResponseHeader("Location").getValue();
                method = new GetMethod(url);
                method.setFollowRedirects(true);
                method.setDoAuthentication(false);
                result = httpClient.executeMethod(method);
                if (externalAuthenticatingProxy && result == 407) {
                    method.releaseConnection();
                    method.setDoAuthentication(true);
                    result = httpClient.executeMethod(method);
                }
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (ProxyClientException e) {
        throw e;
    } catch (Exception e) {
        throw new ProxyClientException("The Proxy request specified by  " + node + " failed, cause follows:",
                e);
    } finally {
        unbindNode();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + node + " does not contain a valid endpoint specification ");
}

From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java

@Override
public String proxifyRequest(String method, String url, Map<String, String> headers) throws Exception {

    HttpMethod httpMtd;
    if (method.equalsIgnoreCase("post")) {
        httpMtd = new PostMethod(url);
    }//from  w ww  .  j a  v  a2s .  co m
    if (method.equalsIgnoreCase("put")) {
        httpMtd = new PutMethod(url);
    }
    if (method.equalsIgnoreCase("delete")) {
        httpMtd = new DeleteMethod(url);
    } else {
        httpMtd = new GetMethod(url);
    }

    if (headers != null) {
        for (String key : headers.keySet()) {
            httpMtd.addRequestHeader(key, headers.get(key));
        }
    }

    HttpClient httpclient = new HttpClient();
    try {
        int result = httpclient.executeMethod(httpMtd);
        if (result != 200) {
            if (httpMtd.getResponseHeader("Error") != null) {
                throw new Exception(httpMtd.getResponseHeader("Error").getValue());
            }
            throw new Exception("Service error code - " + result);
        }
        BufferedInputStream response = new BufferedInputStream(httpMtd.getResponseBodyAsStream());
        ByteArrayOutputStream resultBuffer = new ByteArrayOutputStream();

        byte[] buffer = new byte[1000];
        int i;
        do {
            i = response.read(buffer);
            if (i > 0) {
                resultBuffer.write(buffer, 0, i);
            }
        } while (i > 0);
        httpMtd.releaseConnection();

        return resultBuffer.toString("UTF-8");
    } catch (Exception exc) {
        httpMtd.releaseConnection();
        throw new Exception(exc.getClass().getSimpleName() + " : " + exc.getMessage());
    }
}

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

@Override
public AbstractStorageItem retrieveItem(ProxyRepository repository, ResourceStoreRequest request,
        String baseUrl) throws ItemNotFoundException, RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(baseUrl, request.getRequestPath());

    HttpMethod method;

    method = new GetMethod(remoteURL.toString());

    int response = executeMethod(repository, request, method, remoteURL);

    if (response == HttpStatus.SC_OK) {
        if (method.getPath().endsWith("/")) {
            // this is a collection and not a file!
            // httpClient will follow redirections, and the getPath()
            // _should_
            // give us URL with ending "/"
            method.releaseConnection();/*w  w w  . j  a  v  a2s.  c o m*/

            throw new RemoteItemNotFoundException(request, repository, "remoteIsCollection",
                    remoteURL.toString());
        }

        GetMethod get = (GetMethod) method;

        InputStream is;

        try {
            is = get.getResponseBodyAsStream();
            if (get.getResponseHeader("Content-Encoding") != null
                    && "gzip".equals(get.getResponseHeader("Content-Encoding").getValue())) {
                is = new GZIPInputStream(is);
            }

            String mimeType;

            if (method.getResponseHeader("content-type") != null) {
                mimeType = method.getResponseHeader("content-type").getValue();
            } else {
                mimeType = getMimeSupport().guessMimeTypeFromPath(repository.getMimeRulesSource(),
                        request.getRequestPath());
            }

            DefaultStorageFileItem httpItem = new DefaultStorageFileItem(repository, request, true, true,
                    new PreparedContentLocator(new HttpClientInputStream(get, is), mimeType));

            if (get.getResponseContentLength() != -1) {
                // FILE
                httpItem.setLength(get.getResponseContentLength());
            }

            httpItem.setRemoteUrl(remoteURL.toString());

            httpItem.setModified(makeDateFromHeader(method.getResponseHeader("last-modified")));

            httpItem.setCreated(httpItem.getModified());

            httpItem.getItemContext().putAll(request.getRequestContext());

            return httpItem;
        } catch (IOException ex) {
            method.releaseConnection();

            throw new RemoteStorageException("IO Error during response stream handling [repositoryId=\""
                    + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\""
                    + remoteURL.toString() + "\"]!", ex);
        } catch (RuntimeException ex) {
            method.releaseConnection();

            throw ex;
        }
    } else {
        method.releaseConnection();

        if (response == HttpStatus.SC_NOT_FOUND) {
            throw new RemoteItemNotFoundException(request, repository, "NotFound", remoteURL.toString());
        } else {
            throw new RemoteStorageException("The method execution returned result code " + response
                    + " (expected 200). [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    }
}

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.
 * //from www. java 2s  .  c  o m
 * @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.svenk.redmine.core.client.AbstractRedmineClient.java

/**
 * Execute the given method - handle authentication concerns.
 * //from w ww  .j av a  2  s .co  m
 * @param method
 * @param hostConfiguration
 * @param monitor
 * @param authenticated
 * @return
 * @throws RedmineException
 */
protected int executeMethod(HttpMethod method, HostConfiguration hostConfiguration, IProgressMonitor monitor)
        throws RedmineException {
    monitor = Policy.monitorFor(monitor);

    int statusCode = performExecuteMethod(method, hostConfiguration, monitor);

    if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        Header statusHeader = method.getResponseHeader(HEADER_STATUS);
        String msg = Messages.AbstractRedmineClient_SERVER_ERROR;
        if (statusHeader != null) {
            msg += " : " + statusHeader.getValue().replace("" + HttpStatus.SC_INTERNAL_SERVER_ERROR, "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

        throw new RedmineRemoteException(msg);
    }

    //TODO testen, sollte ohne gehen
    //      if (statusCode==HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
    //         hostConfiguration = refreshCredentials(AuthenticationType.PROXY, method, monitor);
    //         return executeMethod(method, hostConfiguration, monitor, authenticated);
    //      }
    //      
    //      if(statusCode==HttpStatus.SC_UNAUTHORIZED && supportAdditionalHttpAuth()) {
    //         hostConfiguration = refreshCredentials(AuthenticationType.HTTP, method, monitor);
    //         return executeMethod(method, hostConfiguration, monitor, authenticated);
    //      }
    //
    //      if (statusCode>=400 && statusCode<=599) {
    //         throw new RedmineRemoteException(method.getStatusLine().toString());
    //      }

    Header respHeader = method.getResponseHeader(HEADER_REDIRECT);
    if (respHeader != null && (respHeader.getValue().endsWith(REDMINE_URL_LOGIN)
            || respHeader.getValue().indexOf(REDMINE_URL_LOGIN_CALLBACK) >= 0)) {
        throw new RedmineException(Messages.AbstractRedmineClient_LOGIN_FORMALY_INEFFECTIVE);
    }

    return statusCode;
}

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

/**
 * Ask user for name and password.//from w w w . ja v  a2s.c  o  m
 * 
 * @param authenticationType
 * @param method
 * @param monitor
 * @return
 * @throws RedmineException
 */
protected HostConfiguration refreshCredentials(AuthenticationType authenticationType, HttpMethod method,
        IProgressMonitor monitor) throws RedmineException {
    if (Policy.isBackgroundMonitor(monitor)) {
        throw new RedmineAuthenticationException(method.getStatusCode(),
                Messages.AbstractRedmineClient_MISSING_CREDENTIALS_MANUALLY_SYNC_REQUIRED);
    }

    try {
        String message = Messages.AbstractRedmineClient_AUTHENTICATION_REQUIRED;
        if (authenticationType.equals(AuthenticationType.HTTP)) {
            Header authHeader = method.getResponseHeader(HEADER_WWW_AUTHENTICATE);
            if (authHeader != null) {
                for (HeaderElement headerElem : authHeader.getElements()) {
                    if (headerElem.getName().contains(HEADER_WWW_AUTHENTICATE_REALM)) {
                        message += ": " + headerElem.getValue(); //$NON-NLS-1$
                        break;
                    }
                }
            }
        }
        location.requestCredentials(authenticationType, message, monitor);

        return WebUtil.createHostConfiguration(httpClient, location, monitor);
    } catch (UnsupportedRequestException e) {
        IStatus status = RedmineCorePlugin.toStatus(e, null,
                Messages.AbstractRedmineClient_CREDENTIALS_REQUEST_FAILED);
        StatusHandler.log(status);
        throw new RedmineStatusException(status);
    } catch (OperationCanceledException e) {
        monitor.setCanceled(true);
        throw new RedmineException(Messages.AbstractRedmineClient_AUTHENTICATION_CANCELED);
    }
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Execute the supplied HTTP Method./*from w ww .java2  s  .c o m*/
 * <p/>
 * Does not release the {@link org.apache.commons.httpclient.HttpMethod#releaseConnection() HttpMethod connection}.
 *
 * @param method The HTTP Method.
 * @return The HTTP Response.
 */
public String execute(HttpMethod method) {
    if (_httpClient == null) {
        Assert.fail(
                "HTTPMixIn not initialized.  You must call the initialize() method before using this MixIn");
    }

    for (String key : _requestHeaders.keySet()) {
        method.setRequestHeader(key, _requestHeaders.get(key));
    }

    if (_dumpMessages) {
        for (Header header : method.getRequestHeaders()) {
            _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]");
        }
    }

    String response = null;
    try {
        _httpClient.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (Exception e) {
        try {
            Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage());
        } catch (URIException e1) {
            _logger.error("Unexpected error", e1);
            return null;
        }
    }

    if (_dumpMessages) {
        for (Header header : method.getResponseHeaders()) {
            _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]");
        }
        _logger.info("Received response body:[" + response + "]");
    }

    for (String key : _expectedHeaders.keySet()) {
        Header actual = method.getResponseHeader(key);
        Assert.assertNotNull("Checking response header:[" + key + "]", actual);
        Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key),
                actual.getValue());
    }

    return response;
}

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 w  ww.  j a va  2 s. c om*/
        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 w  w  w  . ja  v a 2 s.com*/
    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:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java

public static Response callHttp(String url, String user, String password)
        throws IOException, KettleStepException {

    // used for calculating the responseTime
    long startTime = System.currentTimeMillis();

    HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
    HttpMethod method = new GetMethod(url);
    httpclient.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    httpclient.getState().setCredentials(AuthScope.ANY, credentials);
    HostConfiguration hostConfiguration = new HostConfiguration();

    int status;//from   ww w. j  a  va  2s .  co  m
    try {
        status = httpclient.executeMethod(hostConfiguration, method);
    } catch (IllegalArgumentException ex) {
        status = -1;
    }

    Response response = new Response();
    if (status != -1) {
        String body = null;
        String encoding = "";
        Header contentTypeHeader = method.getResponseHeader("Content-Type");
        if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null && contentType.contains("charset")) {
                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "").replace("\"", "").trim();
            }
        }

        // get the response
        InputStreamReader inputStreamReader = null;
        if (!Const.isEmpty(encoding)) {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), encoding);
        } else {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
        }
        StringBuilder bodyBuffer = new StringBuilder();
        int c;
        while ((c = inputStreamReader.read()) != -1) {
            bodyBuffer.append((char) c);
        }
        inputStreamReader.close();
        body = bodyBuffer.toString();

        // Get response time
        long responseTime = System.currentTimeMillis() - startTime;

        response.setStatusCode(status);
        response.setResult(body);
        response.setResponseTime(responseTime);
    }
    return response;
}