Search in sources :

Example 1 with DefaultProxyRoutePlanner

use of org.apache.http.impl.conn.DefaultProxyRoutePlanner in project ats-framework by Axway.

the class HttpClient method execute.

/**
     * Main execute method that sends request and receives response.
     *
     * @param method The POST/PUT etc. method
     * @return The response
     * @throws HttpException
     */
private HttpResponse execute(HttpRequestBase httpMethod) throws HttpException {
    HttpClientContext localContext = null;
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        // Add this interceptor to get the values of all HTTP headers in the request.
        // Some of them are provided by the user while others are generated by Apache HTTP Components.
        httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {

            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                Header[] requestHeaders = request.getAllHeaders();
                actualRequestHeaders = new ArrayList<HttpHeader>();
                for (Header header : requestHeaders) {
                    addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
                }
                if (debugLevel != HttpDebugLevel.NONE) {
                    logHTTPRequest(requestHeaders, request);
                }
            }
        });
        // Setup authentication
        if (!StringUtils.isNullOrEmpty(username)) {
            localContext = setupAuthentication(httpClientBuilder);
        }
        // Setup SSL
        if (url.toLowerCase().startsWith("https")) {
            setupSSL(httpClientBuilder);
        }
        // all important options are set, now build the HTTP client
        if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {
            HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClient = httpClientBuilder.setRoutePlanner(routePlanner).build();
        } else {
            httpClient = httpClientBuilder.build();
        }
    }
    // Setup read and connect timeouts
    httpMethod.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutSeconds * 1000).setConnectTimeout(connectTimeoutSeconds * 1000).build());
    // Add HTTP headers
    addHeadersToHttpMethod(httpMethod);
    // Create response handler
    ResponseHandler<HttpResponse> responseHandler = new ResponseHandler<HttpResponse>() {

        @Override
        public HttpResponse handleResponse(final org.apache.http.HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            Header[] responseHeaders = response.getAllHeaders();
            List<HttpHeader> responseHeadersList = new ArrayList<HttpHeader>();
            for (Header header : responseHeaders) {
                addHeaderToList(responseHeadersList, header.getName(), header.getValue());
            }
            if ((debugLevel & HttpDebugLevel.HEADERS) == HttpDebugLevel.HEADERS) {
                logHTTPResponse(responseHeaders, response);
            }
            try {
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    // No response body, generally have '204 No content' status
                    return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
                } else {
                    if (responseBodyFilePath != null) {
                        FileOutputStream fos = null;
                        try {
                            fos = new FileOutputStream(new File(responseBodyFilePath), false);
                            entity.writeTo(fos);
                        } finally {
                            IoUtils.closeStream(fos);
                        }
                        return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
                    } else {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        entity.writeTo(bos);
                        return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList, bos.toByteArray());
                    }
                }
            } finally {
                if (response instanceof CloseableHttpResponse) {
                    IoUtils.closeStream((CloseableHttpResponse) response, "Failed to close HttpResponse");
                }
            }
        }
    };
    // Send the request as POST/GET etc. and return response.
    try {
        return httpClient.execute(httpMethod, responseHandler, localContext);
    } catch (IOException e) {
        throw new HttpException("Exception occurred sending message to URL '" + actualUrl + "' with a read timeout of " + readTimeoutSeconds + " seconds and a connect timeout of " + connectTimeoutSeconds + " seconds.", e);
    } finally {
        // clear internal variables
        ActionLibraryConfigurator actionLibraryConfigurator = ActionLibraryConfigurator.getInstance();
        if (!actionLibraryConfigurator.getHttpKeepRequestHeaders()) {
            this.requestHeaders.clear();
        }
        if (!actionLibraryConfigurator.getHttpKeepRequestParameters()) {
            this.requestParameters.clear();
        }
        if (!actionLibraryConfigurator.getHttpKeepRequestBody()) {
            this.requestBody = null;
        }
        this.responseBodyFilePath = null;
    }
}
Also used : ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) ActionLibraryConfigurator(com.axway.ats.action.ActionLibraryConfigurator) ArrayList(java.util.ArrayList) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Header(org.apache.http.Header) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 2 with DefaultProxyRoutePlanner

use of org.apache.http.impl.conn.DefaultProxyRoutePlanner in project jmeter by apache.

the class NonGuiProxySample method main.

public static void main(String[] args) throws IllegalUserActionException, IOException {
    // Or wherever you put it.
    JMeterUtils.setJMeterHome("./");
    JMeterUtils.loadJMeterProperties(JMeterUtils.getJMeterBinDir() + "/jmeter.properties");
    JMeterUtils.initLocale();
    TestPlan testPlan = new TestPlan();
    ThreadGroup threadGroup = new ThreadGroup();
    ListedHashTree testPlanTree = new ListedHashTree();
    testPlanTree.add(testPlan);
    testPlanTree.add(threadGroup, testPlan);
    // deliberate use of deprecated ctor
    @SuppressWarnings("deprecation") JMeterTreeModel treeModel = new JMeterTreeModel(new Object());
    JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
    treeModel.addSubTree(testPlanTree, root);
    ProxyControl proxy = new ProxyControl();
    proxy.setNonGuiTreeModel(treeModel);
    proxy.setTarget(treeModel.getNodeOf(threadGroup));
    proxy.setPort(8282);
    treeModel.addComponent(proxy, (JMeterTreeNode) root.getChildAt(1));
    proxy.startProxy();
    HttpHost proxyHost = new HttpHost("localhost", 8282);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
    CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build();
    try {
        httpclient.execute(new HttpGet("http://example.invalid"));
    } catch (Exception e) {
    //
    }
    proxy.stopProxy();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        SaveService.saveTree(treeModel.getTestPlan(), out);
        out.close();
        System.out.println(out.toString());
    }
}
Also used : ListedHashTree(org.apache.jorphan.collections.ListedHashTree) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) TestPlan(org.apache.jmeter.testelement.TestPlan) HttpGet(org.apache.http.client.methods.HttpGet) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) JMeterTreeModel(org.apache.jmeter.gui.tree.JMeterTreeModel) HttpHost(org.apache.http.HttpHost) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) ThreadGroup(org.apache.jmeter.threads.ThreadGroup)

Aggregations

ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 HttpHost (org.apache.http.HttpHost)2 DefaultProxyRoutePlanner (org.apache.http.impl.conn.DefaultProxyRoutePlanner)2 ActionLibraryConfigurator (com.axway.ats.action.ActionLibraryConfigurator)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 ArrayList (java.util.ArrayList)1 Header (org.apache.http.Header)1 HttpEntity (org.apache.http.HttpEntity)1 HttpRequest (org.apache.http.HttpRequest)1 HttpRequestInterceptor (org.apache.http.HttpRequestInterceptor)1 ResponseHandler (org.apache.http.client.ResponseHandler)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1 HttpGet (org.apache.http.client.methods.HttpGet)1 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)1 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)1 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)1 HttpContext (org.apache.http.protocol.HttpContext)1 IllegalUserActionException (org.apache.jmeter.exceptions.IllegalUserActionException)1