Example usage for org.apache.http.conn.params ConnRoutePNames LOCAL_ADDRESS

List of usage examples for org.apache.http.conn.params ConnRoutePNames LOCAL_ADDRESS

Introduction

In this page you can find the example usage for org.apache.http.conn.params ConnRoutePNames LOCAL_ADDRESS.

Prototype

String LOCAL_ADDRESS

To view the source code for org.apache.http.conn.params ConnRoutePNames LOCAL_ADDRESS.

Click Source Link

Document

Parameter for the local address.

Usage

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.java

public Response sendRequest(SubmitContext submitContext, Request request) throws Exception {
    AbstractHttpRequestInterface<?> httpRequest = (AbstractHttpRequestInterface<?>) request;

    HttpClientSupport.SoapUIHttpClient httpClient = HttpClientSupport.getHttpClient();
    ExtendedHttpMethod httpMethod = createHttpMethod(httpRequest);

    boolean createdContext = false;
    HttpContext httpContext = (HttpContext) submitContext.getProperty(SubmitContext.HTTP_STATE_PROPERTY);
    if (httpContext == null) {
        httpContext = HttpClientSupport.createEmptyContext();
        submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, httpContext);
        createdContext = true;//from   www. j av a 2s  .c o  m
    }

    String localAddress = System.getProperty("soapui.bind.address", httpRequest.getBindAddress());
    if (localAddress == null || localAddress.trim().length() == 0)
        localAddress = SoapUI.getSettings().getString(HttpSettings.BIND_ADDRESS, null);

    org.apache.http.HttpResponse httpResponse = null;
    if (localAddress != null && localAddress.trim().length() > 0) {
        try {
            httpMethod.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS,
                    InetAddress.getByName(localAddress));
        } catch (Exception e) {
            SoapUI.logError(e, "Failed to set localAddress to [" + localAddress + "]");
        }
    }

    submitContext.removeProperty(RESPONSE);
    submitContext.setProperty(HTTP_METHOD, httpMethod);
    submitContext.setProperty(POST_METHOD, httpMethod);
    submitContext.setProperty(HTTP_CLIENT, httpClient);
    submitContext.setProperty(REQUEST_CONTENT, httpRequest.getRequestContent());
    submitContext.setProperty(WSDL_REQUEST, httpRequest);
    submitContext.setProperty(RESPONSE_PROPERTIES, new StringToStringMap());

    for (RequestFilter filter : filters) {
        filter.filterRequest(submitContext, httpRequest);
    }

    try {
        Settings settings = httpRequest.getSettings();

        // custom http headers last so they can be overridden
        StringToStringsMap headers = httpRequest.getRequestHeaders();

        // first remove so we don't get any unwanted duplicates
        for (String header : headers.keySet()) {
            httpMethod.removeHeaders(header);
        }

        // now add
        for (String header : headers.keySet()) {
            for (String headerValue : headers.get(header)) {
                headerValue = PropertyExpander.expandProperties(submitContext, headerValue);
                httpMethod.addHeader(header, headerValue);
            }
        }

        // do request
        WsdlProject project = (WsdlProject) ModelSupport.getModelItemProject(httpRequest);
        WssCrypto crypto = null;
        if (project != null && project.getWssContainer() != null) {
            crypto = project.getWssContainer().getCryptoByName(
                    PropertyExpander.expandProperties(submitContext, httpRequest.getSslKeystore()));
        }

        if (crypto != null && WssCrypto.STATUS_OK.equals(crypto.getStatus())) {
            httpMethod.getParams().setParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG,
                    crypto.getSource() + " " + crypto.getPassword());
        }

        // dump file?
        httpMethod.setDumpFile(PathUtils.expandPath(httpRequest.getDumpFile(),
                (AbstractWsdlModelItem<?>) httpRequest, submitContext));

        // include request time?
        if (settings.getBoolean(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN))
            httpMethod.initStartTime();

        if (httpMethod.getMetrics() != null) {
            httpMethod.getMetrics().setHttpMethod(httpMethod.getMethod());
            captureMetrics(httpMethod, httpClient);
            httpMethod.getMetrics().getTotalTimer().start();
        }

        // submit!
        httpResponse = HttpClientSupport.execute(httpMethod, httpContext);

        // save request headers captured by interceptor
        saveRequestHeaders(httpMethod, httpContext);

        if (httpMethod.getMetrics() != null) {
            httpMethod.getMetrics().getReadTimer().stop();
            httpMethod.getMetrics().getTotalTimer().stop();
        }

        if (isRedirectResponse(httpResponse.getStatusLine().getStatusCode())
                && httpRequest.isFollowRedirects()) {
            if (httpResponse.getEntity() != null) {
                EntityUtils.consume(httpResponse.getEntity());
            }

            ExtendedGetMethod returnMethod = followRedirects(httpClient, 0, httpMethod, httpResponse,
                    httpContext);
            httpMethod = returnMethod;
            submitContext.setProperty(HTTP_METHOD, httpMethod);
        }
    } catch (Throwable t) {
        httpMethod.setFailed(t);

        if (t instanceof Exception)
            throw (Exception) t;

        SoapUI.logError(t);
        throw new Exception(t);
    } finally {
        if (!httpMethod.isFailed()) {
            if (httpMethod.getMetrics() != null) {
                if (httpMethod.getMetrics().getReadTimer().getStop() == 0) {
                    httpMethod.getMetrics().getReadTimer().stop();
                }
                if (httpMethod.getMetrics().getTotalTimer().getStop() == 0) {
                    httpMethod.getMetrics().getTotalTimer().stop();
                }
            }
        } else {
            httpMethod.getMetrics().reset();
            httpMethod.getMetrics().setTimestamp(System.currentTimeMillis());
            captureMetrics(httpMethod, httpClient);
        }

        for (int c = filters.size() - 1; c >= 0; c--) {
            RequestFilter filter = filters.get(c);
            filter.afterRequest(submitContext, httpRequest);
        }

        if (!submitContext.hasProperty(RESPONSE)) {
            createDefaultResponse(submitContext, httpRequest, httpMethod);
        }

        Response response = (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
        StringToStringMap responseProperties = (StringToStringMap) submitContext
                .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

        for (String key : responseProperties.keySet()) {
            response.setProperty(key, responseProperties.get(key));
        }

        if (createdContext) {
            submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, null);
        }
    }

    return (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
}

From source file:com.mgmtp.perfload.core.client.web.config.HttpClientManagerModule.java

/**
 * <p>/*w  w  w  .j  a va  2s. com*/
 * Provides parameter for the HttpClient. This default implementation sets the following
 * parameters:
 * </p>
 * <p>
 * <ul>
 * <li>http.protocol.content-charset: "UTF-8"</li>
 * <li>http.useragent: "perfLoad <code>${perfLoadVersion}</code>"</li>
 * <li>http.protocol.cookie-policy: "best-match"</li>
 * </ul>
 * </p>
 * <p>
 * The default may be overridden using properties with the same names. Additionally, the user
 * agent may also be set in the {@link PlaceholderContainer} in order to vary it during a test,
 * the latter taking precendence over the properties.
 * </p>
 * 
 * @param perfLoadVersion
 *            the perfLoad version (used as part of the user agent string)
 * @return the parameters
 * @see CookiePolicy
 */
@Provides
protected HttpParams provideHttpParams(@PerfLoadVersion final String perfLoadVersion,
        final InetAddress localAddress, final PropertiesMap properties,
        final PlaceholderContainer placeholderContainer) {
    HttpParams params = new BasicHttpParams();

    String charset = properties.get(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);

    String cookiePolicy = properties.get(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    params.setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy);

    params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);

    String userAgent = placeholderContainer.get(CoreProtocolPNames.USER_AGENT);
    if (userAgent == null) {
        userAgent = properties.get(CoreProtocolPNames.USER_AGENT);
        if (userAgent == null) {
            userAgent = "perfLoad " + perfLoadVersion;
        }
    }
    params.setParameter(CoreProtocolPNames.USER_AGENT, userAgent);

    return params;
}

From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java

@Override
public Response sendRequest(SubmitContext submitContext, Request request) throws Exception {
    boolean useSuper = false;

    if (useSuper == true) {
        return super.sendRequest(submitContext, request);
    }/*from  w w w.  j a v  a  2 s.c  om*/
    AbstractHttpRequestInterface<?> httpRequest = (AbstractHttpRequestInterface<?>) request;
    RequestMethod rm = httpRequest.getMethod();

    ExtendedHttpMethod httpMethod;
    switch (rm) {
    case POST: {
        ExtendedPostMethod extendedPostMethod = new ExtendedPostMethod();
        extendedPostMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection());
        httpMethod = extendedPostMethod;
        break;
    }
    case GET: {
        ExtendedGetMethod extendedGetMethod = new ExtendedGetMethod();
        //        extendedGetMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection());
        httpMethod = extendedGetMethod;
        break;
    }
    default:
        throw new IllegalArgumentException("Unsupported HTTP methd: " + rm);
    }

    HttpClientSupport.SoapUIHttpClient httpClient = HttpClientSupport.getHttpClient();

    boolean createdContext = false;
    HttpContext httpContext = (HttpContext) submitContext.getProperty(SubmitContext.HTTP_STATE_PROPERTY);
    if (httpContext == null) {
        httpContext = new BasicHttpContext();
        submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, httpContext);
        createdContext = true;

        // always use local cookie store so we don't share cookies with other threads/executions/requests
        CookieStore cookieStore = new BasicCookieStore();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }

    String localAddress = System.getProperty("soapui.bind.address", httpRequest.getBindAddress());
    if (localAddress == null || localAddress.trim().length() == 0) {
        localAddress = SoapUI.getSettings().getString(HttpSettings.BIND_ADDRESS, null);
    }

    org.apache.http.HttpResponse httpResponse = null;
    if (localAddress != null && localAddress.trim().length() > 0) {
        try {
            httpMethod.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS,
                    InetAddress.getByName(localAddress));
        } catch (Exception e) {
            SoapUI.logError(e, "Failed to set localAddress to [" + localAddress + "]");
        }
    }
    Map<String, String> httpRequestParameter = new HashMap<>();
    if (httpRequest instanceof HttpTestRequest) {
        HttpTestRequest tr = (HttpTestRequest) httpRequest;
        for (String key : tr.getParams().keySet()) {
            RestParamProperty val = tr.getParams().get(key);
            String sval = val.getValue();
            sval = PropertyExpander.expandProperties(submitContext, sval);
            httpRequestParameter.put(key, sval);
        }
    }

    submitContext.removeProperty(RESPONSE);
    submitContext.setProperty(HTTP_METHOD, httpMethod);
    submitContext.setProperty(POST_METHOD, httpMethod);
    submitContext.setProperty(HTTP_CLIENT, httpClient);
    submitContext.setProperty(REQUEST_CONTENT, httpRequest.getRequestContent());
    submitContext.setProperty(WSDL_REQUEST, httpRequest);
    submitContext.setProperty(RESPONSE_PROPERTIES, new StringToStringMap());
    List<RequestFilter> filters = getFilters();
    for (RequestFilter filter : filters) {
        filter.filterRequest(submitContext, httpRequest);
    }

    try {
        Settings settings = httpRequest.getSettings();

        // custom http headers last so they can be overridden
        StringToStringsMap headers = httpRequest.getRequestHeaders();

        // first remove so we don't get any unwanted duplicates
        for (String header : headers.keySet()) {
            httpMethod.removeHeaders(header);
        }

        // now add
        for (String header : headers.keySet()) {
            for (String headerValue : headers.get(header)) {
                headerValue = PropertyExpander.expandProperties(submitContext, headerValue);
                httpMethod.addHeader(header, headerValue);
            }
        }

        // do request
        WsdlProject project = (WsdlProject) ModelSupport.getModelItemProject(httpRequest);
        WssCrypto crypto = null;
        if (project != null && project.getWssContainer() != null) {
            crypto = project.getWssContainer().getCryptoByName(
                    PropertyExpander.expandProperties(submitContext, httpRequest.getSslKeystore()));
        }

        if (crypto != null && WssCrypto.STATUS_OK.equals(crypto.getStatus())) {
            httpMethod.getParams().setParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG,
                    crypto.getSource() + " " + crypto.getPassword());
        }

        // dump file?
        httpMethod.setDumpFile(PathUtils.expandPath(httpRequest.getDumpFile(),
                (AbstractWsdlModelItem<?>) httpRequest, submitContext));

        // include request time?
        if (settings.getBoolean(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN)) {
            httpMethod.initStartTime();
        }

        if (httpMethod.getMetrics() != null) {
            httpMethod.getMetrics().setHttpMethod(httpMethod.getMethod());
            PrivateBeanUtils.invokeMethod(this, "captureMetrics", httpMethod, httpClient);
            httpMethod.getMetrics().getTotalTimer().start();
        }

        // submit!
        httpResponse = execute(submitContext, httpMethod, httpContext, httpRequestParameter);

        if (httpMethod.getMetrics() != null) {
            httpMethod.getMetrics().getReadTimer().stop();
            httpMethod.getMetrics().getTotalTimer().stop();
        }

        //          if (isRedirectResponse(httpResponse.getStatusLine().getStatusCode()) && httpRequest.isFollowRedirects()) {
        //            if (httpResponse.getEntity() != null) {
        //              EntityUtils.consume(httpResponse.getEntity());
        //            }
        //
        //            ExtendedGetMethod returnMethod = followRedirects(httpClient, 0, httpMethod, httpResponse, httpContext);
        //            httpMethod = returnMethod;
        //            submitContext.setProperty(HTTP_METHOD, httpMethod);
        //          }
    } catch (Throwable t) { // NOSONAR "Illegal Catch" framework
        httpMethod.setFailed(t);

        if (t instanceof Exception) {
            throw (Exception) t;
        }

        SoapUI.logError(t);
        throw new Exception(t);
    } finally {
        if (!httpMethod.isFailed()) {
            if (httpMethod.getMetrics() != null) {
                if (httpMethod.getMetrics().getReadTimer().getStop() == 0) {
                    httpMethod.getMetrics().getReadTimer().stop();
                }
                if (httpMethod.getMetrics().getTotalTimer().getStop() == 0) {
                    httpMethod.getMetrics().getTotalTimer().stop();
                }
            }
        } else {
            httpMethod.getMetrics().reset();
            httpMethod.getMetrics().setTimestamp(System.currentTimeMillis());
            //            captureMetrics(httpMethod, httpClient);
        }
        for (int c = filters.size() - 1; c >= 0; c--) {
            RequestFilter filter = filters.get(c);
            filter.afterRequest(submitContext, httpRequest);
        }

        if (!submitContext.hasProperty(RESPONSE)) {
            createDefaultResponse(submitContext, httpRequest, httpMethod);
        }

        Response response = (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
        StringToStringMap responseProperties = (StringToStringMap) submitContext
                .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

        for (String key : responseProperties.keySet()) {
            response.setProperty(key, responseProperties.get(key));
        }

        if (createdContext) {
            submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, null);
        }
    }

    return (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
}

From source file:org.onebusaway.siri.core.SiriCommon.java

/****
 * Setup Methods//w  w  w.  j ava2  s  .c o m
 ****/

@PostConstruct
public void start() {
    HttpParams params = new BasicHttpParams();

    /**
     * Override the default local address used for outgoing http client
     * connections, if specified
     */
    if (_localAddress != null) {
        params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, _localAddress);
    }

    /**
     * Set the timeout for both connections to a socket and for reading from a
     * socket.
     */
    if (_connectionTimeout != 0) {
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout * 1000);
        HttpConnectionParams.setSoTimeout(params, _connectionTimeout * 1000);
    }

    /**
     * We want to allow a fair-amount of concurrent connections. TODO: Can we
     * auto-tune this somehow?
     */
    ConnManagerParams.setMaxTotalConnections(params, 50);

    /**
     * We want to create a connection manager that can pool multiple
     * connections.
     */
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    _client = new DefaultHttpClient(connectionManager, params);
}

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

/**
 * Parses the result and fills the SampleResult with its info
 * @param httpRequest the executed request
 * @param localContext the Http context which was used
 * @param res the SampleResult which is to be filled
 * @param httpResponse the response which is to be parsed
 * @throws IllegalStateException// w  ww.j a v  a  2 s. c  om
 * @throws IOException
 */
private void parseResponse(HttpRequestBase httpRequest, HttpContext localContext, HTTPSampleResult res,
        HttpResponse httpResponse) throws IllegalStateException, IOException {

    // Needs to be done after execute to pick up all the headers
    final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    // We've finished with the request, so we can add the LocalAddress to it for display
    final InetAddress localAddr = (InetAddress) httpRequest.getParams()
            .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
    if (localAddr != null) {
        request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
    }
    res.setRequestHeaders(getConnectionHeaders(request));

    Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
    if (contentType != null) {
        String ct = contentType.getValue();
        res.setContentType(ct);
        res.setEncodingAndType(ct);
    }
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        res.setResponseData(readResponse(res, instream, (int) entity.getContentLength()));
    }

    res.sampleEnd(); // Done with the sampling proper.
    currentRequest = null;

    // Now collect the results into the HTTPSampleResult:
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    res.setResponseCode(Integer.toString(statusCode));
    res.setResponseMessage(statusLine.getReasonPhrase());
    res.setSuccessful(isSuccessCode(statusCode));

    res.setResponseHeaders(getResponseHeaders(httpResponse));
    if (res.isRedirect()) {
        final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
        if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
            throw new IllegalArgumentException(
                    "Missing location header in redirect for " + httpRequest.getRequestLine());
        }
        String redirectLocation = headerLocation.getValue();
        res.setRedirectLocation(redirectLocation);
    }

    // record some sizes to allow HTTPSampleResult.getBytes() with different options
    HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
    long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
            + httpResponse.getAllHeaders().length // Add \r for each header
            + 1 // Add \r for initial header
            + 2; // final \r\n before data
    long totalBytes = metrics.getReceivedBytesCount();
    res.setHeadersSize((int) headerBytes);
    res.setBodySize((int) (totalBytes - headerBytes));
    if (log.isDebugEnabled()) {
        log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                + " Total=" + (res.getHeadersSize() + res.getBodySize()));
    }

    // If we redirected automatically, the URL may have changed
    if (getAutoRedirects()) {
        HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        URI redirectURI = req.getURI();
        if (redirectURI.isAbsolute()) {
            res.setURL(redirectURI.toURL());
        } else {
            res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
        }
    }
}

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

/**
 * Setup following elements on httpRequest:
 * <ul>//w  w  w. ja  va 2s .  c  o  m
 * <li>ConnRoutePNames.LOCAL_ADDRESS enabling IP-SPOOFING</li>
 * <li>Socket and connection timeout</li>
 * <li>Redirect handling</li>
 * <li>Keep Alive header or Connection Close</li>
 * <li>Calls setConnectionHeaders to setup headers</li>
 * <li>Calls setConnectionCookie to setup Cookie</li>
 * </ul>
 * 
 * @param url
 *            {@link URL} of the request
 * @param httpRequest
 *            http request for the request
 * @param res
 *            sample result to set cookies on
 * @throws IOException
 *             if hostname/ip to use could not be figured out
 */
protected void setupRequest(URL url, HttpRequestBase httpRequest, HTTPSampleResult res) throws IOException {

    HttpParams requestParams = httpRequest.getParams();

    // 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')
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, inetAddr);
    } else if (localAddress != null) {
        requestParams.setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
    } else { // reset in case was set previously
        requestParams.removeParameter(ConnRoutePNames.LOCAL_ADDRESS);
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cto);
    }

    requestParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, 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()) {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpRequest, url, getHeaderManager(), getCacheManager());

    String cookies = setConnectionCookie(httpRequest, url, getCookieManager());

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

}

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

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }/*from www. ja v a2  s  .  c  om*/

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}