Example usage for org.apache.http.protocol BasicHttpContext setAttribute

List of usage examples for org.apache.http.protocol BasicHttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext setAttribute.

Prototype

public void setAttribute(String str, Object obj) 

Source Link

Usage

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {
    HttpGet httpget = null;//w  ww  . j  a v  a  2 s  .  c  om

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    httpget = new HttpGet(path);
    httpget.addHeader("Accept-Language", "en");
    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        httpget.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    HttpGet httpget = new HttpGet(path);
    for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
        LOG.info("adding request-header: {}={}", entry.getKey(), entry.getValue());
        httpget.addHeader(entry.getKey(), entry.getValue());
    }//w  w w  . jav  a2 s .  c  o m

    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth
        // cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) {
    if (depth >= MAX_REDIRECT) {
        throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached");
    }/*from w  w  w .j ava2 s  . c  o m*/

    RequestCallback callback = req.getRequestCallback();

    HttpRequestBase method = req.getMethod();
    String verificationText = req.getVerificationText();
    String url = method.getURI().toString();

    // save the browser and version if it's not yet been set
    if (har != null && har.getLog().getBrowser() == null) {
        Header[] uaHeaders = method.getHeaders("User-Agent");
        if (uaHeaders != null && uaHeaders.length > 0) {
            String userAgent = uaHeaders[0].getValue();
            try {
                // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0'
                ReadableUserAgent uai = PARSER.parse(userAgent);
                String browser = uai.getName();
                String version = uai.getVersionNumber().toVersionString();
                har.getLog().setBrowser(new HarNameVersion(browser, version));
            } catch (Exception e) {
                LOG.warn("Failed to parse user agent string", e);
            }
        }
    }

    // process any rewrite requests
    boolean rewrote = false;
    String newUrl = url;
    for (RewriteRule rule : rewriteRules) {
        Matcher matcher = rule.match.matcher(newUrl);
        newUrl = matcher.replaceAll(rule.replace);
        rewrote = true;
    }

    if (rewrote) {
        try {
            method.setURI(new URI(newUrl));
            url = newUrl;
        } catch (URISyntaxException e) {
            LOG.warn("Could not rewrite url to %s", newUrl);
        }
    }

    // handle whitelist and blacklist entries
    int mockResponseCode = -1;
    synchronized (this) {
        // guard against concurrent modification of whitelistEntry
        if (whitelistEntry != null) {
            boolean found = false;
            for (Pattern pattern : whitelistEntry.patterns) {
                if (pattern.matcher(url).matches()) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                mockResponseCode = whitelistEntry.responseCode;
            }
        }
    }

    if (blacklistEntries != null) {
        for (BlacklistEntry blacklistEntry : blacklistEntries) {
            if (blacklistEntry.pattern.matcher(url).matches()) {
                mockResponseCode = blacklistEntry.responseCode;
                break;
            }
        }
    }

    if (!additionalHeaders.isEmpty()) {
        // Set the additional headers
        for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            method.removeHeaders(key);
            method.addHeader(key, value);
        }
    }

    String charSet = "UTF-8";
    String responseBody = null;

    InputStream is = null;
    int statusCode = -998;
    long bytes = 0;
    boolean gzipping = false;
    boolean contentMatched = true;
    OutputStream os = req.getOutputStream();
    if (os == null) {
        os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB
    }
    if (verificationText != null) {
        contentMatched = false;
    }

    // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down)
    // we still have the attempt associated, even if we never got a response
    HarEntry entry = new HarEntry(harPageRef);

    // clear out any connection-related information so that it's not stale from previous use of this thread.
    RequestInfo.clear(url, entry);

    entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol()));
    entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol()));
    if (this.har != null && harPageRef != null) {
        har.getLog().addEntry(entry);
    }

    String query = method.getURI().getRawQuery();
    if (query != null) {
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(query, params, "UTF-8");
        for (String k : params.keySet()) {
            for (Object v : params.getValues(k)) {
                entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v));
            }
        }
    }

    String errorMessage = null;
    HttpResponse response = null;

    BasicHttpContext ctx = new BasicHttpContext();

    ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime());
    synchronized (activeRequests) {
        activeRequests.add(activeRequest);
    }

    // for dealing with automatic authentication
    if (authType == AuthType.NTLM) {
        // todo: not supported yet
        //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine()));
    } else if (authType == AuthType.BASIC) {
        ctx.setAttribute("preemptive-auth", new BasicScheme());
    }

    StatusLine statusLine = null;
    try {
        // set the User-Agent if it's not already set
        if (method.getHeaders("User-Agent").length == 0) {
            method.addHeader("User-Agent", "BrowserMob VU/1.0");
        }

        // was the request mocked out?
        if (mockResponseCode != -1) {
            statusCode = mockResponseCode;

            // TODO: HACKY!!
            callback.handleHeaders(new Header[] { new Header() {
                @Override
                public String getName() {
                    return "Content-Type";
                }

                @Override
                public String getValue() {
                    return "text/plain";
                }

                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
            } });
            // Make sure we set the status line here too.
            // Use the version number from the request
            ProtocolVersion version = null;
            int reqDotVersion = req.getProxyRequest().getDotVersion();
            if (reqDotVersion == -1) {
                version = new HttpVersion(0, 9);
            } else if (reqDotVersion == 0) {
                version = new HttpVersion(1, 0);
            } else if (reqDotVersion == 1) {
                version = new HttpVersion(1, 1);
            }
            // and if not any of these, trust that a Null version will
            // cause an appropriate error
            callback.handleStatusLine(
                    new BasicStatusLine(version, statusCode, "Status set by browsermob-proxy"));
            // No mechanism to look up the response text by status code,
            // so include a notification that this is a synthetic error code.
        } else {
            response = httpClient.execute(method, ctx);
            statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            if (callback != null) {
                callback.handleStatusLine(statusLine);
                callback.handleHeaders(response.getAllHeaders());
            }

            if (response.getEntity() != null) {
                is = response.getEntity().getContent();
            }

            // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204)
            if (is != null) {
                Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
                if (contentEncodingHeader != null
                        && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
                    gzipping = true;
                }

                // deal with GZIP content!
                if (decompress && gzipping) {
                    is = new GZIPInputStream(is);
                }

                if (captureContent) {
                    // todo - something here?
                    os = new ClonedOutputStream(os);
                }

                bytes = copyWithStats(is, os);
            }
        }
    } catch (Exception e) {
        errorMessage = e.toString();

        if (callback != null) {
            callback.reportError(e);
        }

        // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored)
        if (!shutdown) {
            LOG.info(String.format("%s when requesting %s", errorMessage, url));
        }
    } finally {
        // the request is done, get it out of here
        synchronized (activeRequests) {
            activeRequests.remove(activeRequest);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // this is OK to ignore
            }
        }
    }

    // record the response as ended
    RequestInfo.get().finish();

    // set the start time and other timings
    entry.setStartedDateTime(RequestInfo.get().getStart());
    entry.setTimings(RequestInfo.get().getTimings());
    entry.setServerIPAddress(RequestInfo.get().getResolvedAddress());
    entry.setTime(RequestInfo.get().getTotalTime());

    // todo: where you store this in HAR?
    // obj.setErrorMessage(errorMessage);
    entry.getResponse().setBodySize(bytes);
    entry.getResponse().getContent().setSize(bytes);
    entry.getResponse().setStatus(statusCode);
    if (statusLine != null) {
        entry.getResponse().setStatusText(statusLine.getReasonPhrase());
    }

    boolean urlEncoded = false;
    if (captureHeaders || captureContent) {
        for (Header header : method.getAllHeaders()) {
            if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) {
                urlEncoded = true;
            }

            entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
        }

        if (response != null) {
            for (Header header : response.getAllHeaders()) {
                entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
            }
        }
    }

    if (captureContent) {
        // can we understand the POST data at all?
        if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) {
            HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method;
            HttpEntity entity = enclosingReq.getEntity();

            HarPostData data = new HarPostData();
            data.setMimeType(req.getMethod().getFirstHeader("Content-Type").getValue());
            entry.getRequest().setPostData(data);

            if (urlEncoded || URLEncodedUtils.isEncoded(entity)) {
                try {
                    final String content = new String(req.getCopy().toByteArray(), "UTF-8");
                    if (content != null && content.length() > 0) {
                        List<NameValuePair> result = new ArrayList<NameValuePair>();
                        URLEncodedUtils.parse(result, new Scanner(content), null);

                        ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>();
                        data.setParams(params);

                        for (NameValuePair pair : result) {
                            params.add(new HarPostDataParam(pair.getName(), pair.getValue()));
                        }
                    }
                } catch (Exception e) {
                    LOG.info("Unexpected problem when parsing input copy", e);
                }
            } else {
                // not URL encoded, so let's grab the body of the POST and capture that
                data.setText(new String(req.getCopy().toByteArray()));
            }
        }
    }

    //capture request cookies
    javax.servlet.http.Cookie[] cookies = req.getProxyRequest().getCookies();
    for (javax.servlet.http.Cookie cookie : cookies) {
        HarCookie hc = new HarCookie();
        hc.setName(cookie.getName());
        hc.setValue(cookie.getValue());
        entry.getRequest().getCookies().add(hc);
    }

    String contentType = null;

    if (response != null) {
        try {
            Header contentTypeHdr = response.getFirstHeader("Content-Type");
            if (contentTypeHdr != null) {
                contentType = contentTypeHdr.getValue();
                entry.getResponse().getContent().setMimeType(contentType);

                if (captureContent && os != null && os instanceof ClonedOutputStream) {
                    ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput();

                    if (gzipping) {
                        // ok, we need to decompress it before we can put it in the har file
                        try {
                            InputStream temp = new GZIPInputStream(
                                    new ByteArrayInputStream(copy.toByteArray()));
                            copy = new ByteArrayOutputStream();
                            IOUtils.copy(temp, copy);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (hasTextualContent(contentType)) {
                        setTextOfEntry(entry, copy, contentType);
                    } else if (captureBinaryContent) {
                        setBinaryContentOfEntry(entry, copy);
                    }
                }

                NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset");

                if (nvp != null) {
                    charSet = nvp.getValue();
                }
            }

            if (os instanceof ByteArrayOutputStream) {
                responseBody = ((ByteArrayOutputStream) os).toString(charSet);

                if (verificationText != null) {
                    contentMatched = responseBody.contains(verificationText);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    if (contentType != null) {
        entry.getResponse().getContent().setMimeType(contentType);
    }

    // checking to see if the client is being redirected
    boolean isRedirect = false;

    String location = null;
    if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) {
        isRedirect = true;

        // pulling the header for the redirect
        Header locationHeader = response.getLastHeader("location");
        if (locationHeader != null) {
            location = locationHeader.getValue();
        } else if (this.followRedirects) {
            throw new RuntimeException("Invalid redirect - missing location header");
        }
    }

    //
    // Response validation - they only work if we're not following redirects
    //

    int expectedStatusCode = req.getExpectedStatusCode();

    // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem
    if (mockResponseCode == -1 && expectedStatusCode > -1) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }
        if (expectedStatusCode != statusCode) {
            if (isRedirect) {
                throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw "
                        + statusCode + " redirecting to: " + location);
            } else {
                throw new RuntimeException(
                        "Expected status code of " + expectedStatusCode + " but saw " + statusCode);
            }
        }
    }

    // Location header check:
    if (isRedirect && (req.getExpectedLocation() != null)) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }

        if (location.compareTo(req.getExpectedLocation()) != 0) {
            throw new RuntimeException(
                    "Expected a redirect to  " + req.getExpectedLocation() + " but saw " + location);
        }
    }

    // end of validation logic

    // basic tail recursion for redirect handling
    if (isRedirect && this.followRedirects) {
        // updating location:
        try {
            URI redirectUri = new URI(location);
            URI newUri = method.getURI().resolve(redirectUri);
            method.setURI(newUri);

            return execute(req, ++depth);
        } catch (URISyntaxException e) {
            LOG.warn("Could not parse URL", e);
        }
    }

    return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage,
            responseBody, contentType, charSet);
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieSubmitJob(String user, String password, String request, int status)
        throws IOException, URISyntaxException {
    getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED)
            .content(getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    //System.out.println( "REQUEST LENGTH = " + request.length() );

    URL url = new URL(getUrl("OOZIE") + "/v1/jobs?action=start" + (isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost(url.toURI());
    //    post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);// w w w  . j  av  a  2 s. co  m
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());

    //    String json = given()
    //        .log().all()
    //        .auth().preemptive().basic( user, password )
    //        .queryParam( "action", "start" )
    //        .contentType( "application/xml;charset=UTF-8" )
    //        .content( request )
    //        .expect()
    //        .log().all()
    //        .statusCode( status )
    //        .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    //System.out.println( "JSON=" + json );
    String id = from(json).getString("id");
    return id;
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieQueryJobStatus(String user, String password, String id, int status) throws Exception {
    getMock("OOZIE").expect().method("GET").pathInfo("/v1/job/" + id).respond().status(HttpStatus.SC_OK)
            .content(getResourceBytes("oozie-job-show-info.json")).contentType("application/json");

    //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
    URL url = new URL(getUrl("OOZIE") + "/v1/job/" + id + (isUseGateway() ? "" : "?user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet request = new HttpGet(url.toURI());
    request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
    HttpResponse response = client.execute(targetHost, request, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());
    String jobStatus = from(json).getString("status");
    return jobStatus;
}

From source file:org.apache.hive.ptest.execution.JIRAService.java

void publishComments(String comments) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*  ww w.  j a  v  a  2 s. c om*/
        String url = String.format("%s/rest/api/2/issue/%s/comment", mUrl, mName);
        URL apiURL = new URL(mUrl);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(apiURL.getHost(), apiURL.getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(mUser, mPassword));
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute("preemptive-auth", new BasicScheme());
        httpClient.addRequestInterceptor(new PreemptiveAuth(), 0);
        HttpPost request = new HttpPost(url);
        ObjectMapper mapper = new ObjectMapper();
        StringEntity params = new StringEntity(mapper.writeValueAsString(new Body(comments)));
        request.addHeader("Content-Type", "application/json");
        request.setEntity(params);
        HttpResponse httpResponse = httpClient.execute(request, localcontext);
        StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() != 201) {
            throw new RuntimeException(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        }
        mLogger.info("JIRA Response Metadata: " + httpResponse);
    } catch (Exception e) {
        mLogger.error("Encountered error attempting to post comment to " + mName, e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler)
        throws IOException {
    String protocol = _isSecure ? "https" : "http";
    ServiceError error;//  w  w  w  .  j  av  a2s . c  o m
    URL url = new URL(protocol, _host, _port, uri);

    try {
        method.setURI(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e);
    }

    _log.debug("Setting URI: " + url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (_isSecure) {
        // To allow for self signed certificates
        configureSSL(client);
    }

    // Validate user & password inputs
    if (_user == null || _user.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("User name cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    if (_password == null || _password.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("Password cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    // Set Basic auth creds
    UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password);

    client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

    // Preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost(_host, _port, protocol);

    authCache.put(host, basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    // Disable re-tries
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));

    HttpResponse response = client.execute(method, localContext);

    return responseHandler.handleResponse(response);
}