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

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

Introduction

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

Prototype

@Override
public void setFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)

Usage

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int logout() {
    log.finest("Logout");
    try {/*from w  ww  .jav  a2 s .  c  o m*/
        log.finest("URI:" + url.toURI().toString());
    } catch (URISyntaxException ex) {
        log.finest("Logout URISyntaxException " + ex.getMessage());
    }

    String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL;
    log.finest("Attempting to log out with this url: " + logoutUrl);
    HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL);
    authenticationMethod.setFollowRedirects(false);
    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState()
            .getCredentials(new AuthScope(host, port));
    if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) {

        log.finest(String.format("Adding authorizationheadder for logout for user: %s",
                credentials.getUserName()));
        authenticationMethod.addRequestHeader("Authorization:",
                "Base " + credentials.getUserName() + ":" + credentials.getPassword());
    }
    String body = "";
    String status = "";
    int responseCode = 0;
    ;
    try {
        responseCode = executeMethod(authenticationMethod);
        body = authenticationMethod.getResponseBodyAsString();
        status = authenticationMethod.getStatusText();
        log.finest(String.format("Response code %s, Status text %s", responseCode, status));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to log out!", e);
        log.log(Level.SEVERE, body);
    }
    return responseCode;
}

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

/**
 * Can be overriden to tune the default behaviour,
 * check or build parameters.../*  w  w  w.j  a  va  2  s .c  o m*/
 * The client should set the params (query string) itself.
 */
public HttpMethodBase createMethod() throws RestClientException {
    // instantiating a new method and configuring it
    HttpMethodBase method;
    switch (this.getMethodType()) {
    case POST:
        //case PUT:
        method = new PostMethod();
        break;
    case GET:
    default:
        method = new GetMethod();
        method.setFollowRedirects(true);
    }
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    //method.setQueryString(params.toArray(new NameValuePair[0])); // done in client
    //method.getParams().setContentCharset(this.restEncoding); // done in client

    // set request entity (allow to fill method body for posts) :
    if (requestEntity != null && method instanceof EntityEnclosingMethod) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
    }

    return method;
}

From source file:jeeves.utils.XmlRequest.java

private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException {
    HttpMethodBase httpMethod;

    if (method == Method.GET) {
        httpMethod = new GetMethod();

        if (query != null && !query.equals(""))
            httpMethod.setQueryString(query);

        else if (alSimpleParams.size() != 0)
            httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()]));

        httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod.setFollowRedirects(true);
    } else {//from w w  w  .  ja  va 2 s .  c o  m
        PostMethod post = new PostMethod();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8"));
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8"));
        }

        httpMethod = post;
    }

    httpMethod.setPath(address);
    httpMethod.setDoAuthentication(useAuthent());

    return httpMethod;
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

private int makeRequest(HttpMethodBase httpMethod) throws HttpException, IOException, InterruptedException {
    if (Config.debug) {
        System.out.println("DEBUG Worker[" + threadId + "]: " + httpMethod.getName() + " : " + url.toString());
    }/*  w w  w  . j  a  v  a  2 s  .c o  m*/

    // set the custom HTTP headers
    Vector HTTPheaders = manager.getHTTPHeaders();
    for (int a = 0; a < HTTPheaders.size(); a++) {
        HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
        /*
         * Host header has to be set in a different way!
         */
        if (httpHeader.getHeader().startsWith("Host")) {
            httpMethod.getParams().setVirtualHost(httpHeader.getValue());
        } else {
            httpMethod.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
        }
    }
    httpMethod.setFollowRedirects(Config.followRedirects);

    /*
     * this code is used to limit the number of request/sec
     */
    if (manager.isLimitRequests()) {
        while (manager.getTotalDone()
                / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0) > manager
                        .getLimitRequestsTo()) {
            Thread.sleep(100);
        }
    }
    /*
     * Send the request
     */
    int code = httpclient.executeMethod(httpMethod);

    if (Config.debug) {
        System.out.println("DEBUG Worker[" + threadId + "]: " + code + " " + url.toString());
    }
    return code;
}

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Process a page.//from  w w w .  java 2  s  .c  o m
 */
public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        targetURL = new URI(target);
    } catch (URISyntaxException e) {
        IOException ioe = new IOException("Bad URI syntax: " + target);
        ioe.initCause(e);
        throw ioe;
    }
    setHostPrefix(targetURL);

    HttpClient httpClient = new HttpClient();
    HttpState httpState = new HttpState();
    HostConfiguration hostConfig = new HostConfiguration();
    HttpMethodBase httpMethod;

    // define host
    hostConfig.setHost(targetURL.getHost(), targetURL.getPort());

    // create http method
    String method = (String) request.getAttribute("cq.ext.app.method");
    if (method == null) {
        method = request.getMethod();
    }
    method = method.toUpperCase();
    boolean isPost = "POST".equals(method);
    String urlString = targetURL.getPath();
    StringBuffer query = new StringBuffer();
    if (targetURL.getQuery() != null) {
        query.append("?");
        query.append(targetURL.getQuery());
    }
    //------------ GET ---------------
    if ("GET".equals(method)) {
        // add internal props
        Iterator<String> iter = extraParams.keySet().iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String value = extraParams.get(name);
            if (query.length() == 0) {
                query.append("?");
            } else {
                query.append("&");
            }
            query.append(Text.escape(name));
            query.append("=");
            query.append(Text.escape(value));
        }
        if (passInput) {
            // add request params
            @SuppressWarnings("unchecked")
            Enumeration<String> e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                if (targetParamName.equals(name)) {
                    continue;
                }
                String[] values = request.getParameterValues(name);
                for (int i = 0; i < values.length; i++) {
                    if (query.length() == 0) {
                        query.append("?");
                    } else {
                        query.append("&");
                    }
                    query.append(Text.escape(name));
                    query.append("=");
                    query.append(Text.escape(values[i]));
                }
            }

        }
        httpMethod = new GetMethod(urlString + query);
        //------------ POST ---------------
    } else if ("POST".equals(method)) {
        PostMethod m = new PostMethod(urlString + query);
        httpMethod = m;
        String contentType = request.getContentType();
        boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
        if (mp) {
            //------------ MULTPART POST ---------------
            List<Part> parts = new LinkedList<Part>();
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                parts.add(new StringPart(name, value));
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        parts.add(new StringPart(name, values[i]));
                    }
                }
            }
            m.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams()));
        } else {
            //------------ NORMAL POST ---------------
            // add internal props
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                m.addParameter(name, value);
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        m.addParameter(name, values[i]);
                    }
                }
            }
        }
    } else {
        log.error("Unsupported method ''{0}''", method);
        throw new IOException("Unsupported http method " + method);
    }
    log.debug("created http connection for method {0} to {1}", method, urlString + query);

    // add some request headers
    httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent"));
    httpMethod.setFollowRedirects(!isPost);
    httpMethod.getParams().setSoTimeout(soTimeout);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // send request
    httpClient.executeMethod(hostConfig, httpMethod, httpState);
    String contentType = httpMethod.getResponseHeader("Content-Type").getValue();

    log.debug("External app responded: {0}", httpMethod.getStatusLine());
    log.debug("External app contenttype: {0}", contentType);

    // check response code
    int statusCode = httpMethod.getStatusCode();
    if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) {
        PrintWriter writer = response.getWriter();
        writer.println("External application returned status code: " + statusCode);
        return;
    } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
        String location = httpMethod.getResponseHeader("Location").getValue();
        if (location == null) {
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
            return;
        }
        response.sendRedirect(rewriteURL(location, false));
        return;
    }

    // open input stream
    InputStream in = httpMethod.getResponseBodyAsStream();

    // check content type
    if (contentType != null && contentType.startsWith("text/html")) {
        rewriteHtml(in, contentType, response);
    } else {
        // binary mode
        if (contentType != null) {
            response.setContentType(contentType);
        }
        OutputStream outs = response.getOutputStream();

        try {
            byte buf[] = new byte[8192];
            int len;

            while ((len = in.read(buf)) != -1) {
                outs.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:com.ning.http.client.providers.apache.TestableApacheAsyncHttpProvider.java

/**
 * This one we can get into/*from   www  .jav a  2 s.  c  om*/
 */
protected HttpMethodBase getHttpMethodBase(HttpClient client, Request request) throws IOException {
    String methodName = request.getMethod();
    HttpMethodBase method;
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            try (FileInputStream fis = new FileInputStream(file)) {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        if (request.getHeaders().getFirstValue("Expect") != null
                && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else {
        method = testMethodFactory.createMethod(methodName, request);
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultCredentials = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM),
                    defaultCredentials);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    if (isNonEmpty(request.getCookies())) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(TestableApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (!acceptableEncodings.contains("gzip")) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);//from w ww .j  a  va2s  .  c  o  m
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        if (request.getHeaders().getFirstValue("Expect") != null
                && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer()
            : config.getProxyServer();
    boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
    if (!avoidProxy) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }

    method.setFollowRedirects(false);
    if ((request.getCookies() != null) && !request.getCookies().isEmpty()) {
        for (Cookie cookie : request.getCookies()) {
            method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
        }
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Returns an <code>HttpConnection</code> fully ready to attempt
 * connection. This means it sets the request method (GET or POST), headers,
 * cookies, and authorization for the URL request.
 * <p>// ww w  .  ja  v a  2s. co  m
 * The request infos are saved into the sample result if one is provided.
 *
 * @param u
 *            <code>URL</code> of the URL request
 * @param httpMethod
 *            GET/PUT/HEAD etc
 * @param res
 *            sample result to save request infos to
 * @return <code>HttpConnection</code> ready for .connect
 * @exception IOException
 *                if an I/O Exception occurs
 */
protected HttpClient setupConnection(URL u, HttpMethodBase httpMethod, HTTPSampleResult res)
        throws IOException {

    String urlStr = u.toString();

    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(urlStr, false);

    String schema = uri.getScheme();
    if ((schema == null) || (schema.length() == 0)) {
        schema = HTTPConstants.PROTOCOL_HTTP;
    }

    final boolean isHTTPS = HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(schema);
    if (isHTTPS) {
        SSLManager.getInstance(); // ensure the manager is initialised
        // we don't currently need to do anything further, as this sets the default https protocol
    }

    Protocol protocol = Protocol.getProtocol(schema);

    String host = uri.getHost();
    int port = uri.getPort();

    /*
     *  We use the HostConfiguration as the key to retrieve the HttpClient,
     *  so need to ensure that any items used in its equals/hashcode methods are
     *  not changed after use, i.e.:
     *  host, port, protocol, localAddress, proxy
     *
    */
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, port, protocol); // All needed to ensure re-usablility

    // Set up the local address if one exists
    final InetAddress inetAddr = getIpSourceAddress();
    if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
        hc.setLocalAddress(inetAddr);
    } else {
        hc.setLocalAddress(localAddress); // null means use the default
    }

    final String proxyHost = getProxyHost();
    final int proxyPort = getProxyPortInt();

    boolean useStaticProxy = isStaticProxy(host);
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);

    if (useDynamicProxy) {
        hc.setProxy(proxyHost, proxyPort);
        useStaticProxy = false; // Dynamic proxy overrules static proxy
    } else if (useStaticProxy) {
        if (log.isDebugEnabled()) {
            log.debug("Setting proxy: " + PROXY_HOST + ":" + PROXY_PORT);
        }
        hc.setProxy(PROXY_HOST, PROXY_PORT);
    }

    Map<HostConfiguration, HttpClient> map = httpClients.get();
    // N.B. HostConfiguration.equals() includes proxy settings in the compare.
    HttpClient httpClient = map.get(hc);

    if (httpClient != null && resetSSLContext && isHTTPS) {
        httpClient.getHttpConnectionManager().closeIdleConnections(-1000);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) {
        httpClient = new HttpClient(new SimpleHttpConnectionManager());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(RETRY_COUNT, false));
        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient));
        }
        httpClient.setHostConfiguration(hc);
        map.put(hc, httpClient);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient));
        }
    }

    // Set up any required Proxy credentials
    if (useDynamicProxy) {
        String user = getProxyUser();
        if (user.length() > 0) {
            httpClient.getState().setProxyCredentials(
                    new AuthScope(proxyHost, proxyPort, null, AuthScope.ANY_SCHEME),
                    new NTCredentials(user, getProxyPass(), localHost, PROXY_DOMAIN));
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    } else {
        if (useStaticProxy) {
            if (PROXY_USER.length() > 0) {
                httpClient.getState().setProxyCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT, null, AuthScope.ANY_SCHEME),
                        new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN));
            }
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        httpMethod.getParams().setSoTimeout(rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(cto);
    }

    // Allow HttpClient to handle the redirects:
    httpMethod.setFollowRedirects(getAutoRedirects());

    // a well-behaved browser is supposed to send 'Connection: close'
    // with the last request to an HTTP server. Instead, most browsers
    // leave it to the server to close the connection after their
    // timeout period. Leave it to the JMeter user to decide.
    if (getUseKeepAlive()) {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpMethod, u, getHeaderManager(), getCacheManager());
    String cookies = setConnectionCookie(httpMethod, u, getCookieManager());

    setConnectionAuthorization(httpClient, u, getAuthManager());

    if (res != null) {
        res.setCookies(cookies);
    }

    return httpClient;
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.issues.SLING2082Test.java

private void runTest(HttpMethodBase m, int expectedStatus) throws Exception {
    m.setFollowRedirects(false);
    final int status = httpClient.executeMethod(m);
    assertEquals(expectedStatus, status);
    final String content = getResponseBodyAsStream(m, 0);
    final String scriptTag = "<script>";
    assertFalse("Content should not contain '" + scriptTag + "'", content.contains(scriptTag));
}

From source file:org.appcelerator.transport.ProxyTransportServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    String url = request.getParameter("url");
    if (url == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from   w w  w  .  ja  v  a2s.c  o  m
    }

    url = URLDecoder.decode(url, "UTF-8");

    if (url.indexOf("://") == -1) {
        url = new String(Base64.decode(url));
    }

    HttpClient client = new HttpClient();
    HttpMethodBase methodBase = null;

    if (method.equalsIgnoreCase("POST")) {
        methodBase = new PostMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PostMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("GET")) {
        methodBase = new GetMethod(url);
        methodBase.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("PUT")) {
        methodBase = new PutMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PutMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("DELETE")) {
        methodBase = new DeleteMethod(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        methodBase = new OptionsMethod(url);
    }

    methodBase.setRequestHeader("User-Agent", request.getHeader("user-agent") + " (Appcelerator Proxy)");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Proxying url: " + url + ", method: " + method);
    }

    int status = client.executeMethod(methodBase);

    response.setStatus(status);
    response.setContentLength((int) methodBase.getResponseContentLength());

    for (Header header : methodBase.getResponseHeaders()) {
        String name = header.getName();
        if (name.equalsIgnoreCase("Set-Cookie") == false && name.equals("Transfer-Encoding") == false) {
            response.setHeader(name, header.getValue());
        }
    }
    InputStream in = methodBase.getResponseBodyAsStream();
    Util.copy(in, response.getOutputStream());
}