List of usage examples for org.apache.http.client.methods HttpRequestBase setURI
public void setURI(final URI uri)
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;//ww w .j a va 2 s. c om 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); }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
/** * Handles the necessary handshake for digest authenticaion in the case where it isn't a GET operation. * /*from w w w. jav a2 s. c o m*/ * @param httpUriRequest * The request location to get the digest authentication for. * @param httpClient * The client to send the request through. * @throws TrustedHttpClientException * Thrown if the client cannot be shutdown. */ private void manuallyHandleDigestAuthentication(HttpUriRequest httpUriRequest, HttpClient httpClient) throws TrustedHttpClientException { HttpRequestBase digestRequest; try { digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName()); } digestRequest.setURI(httpUriRequest.getURI()); digestRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); String[] realmAndNonce = getRealmAndNonce(digestRequest); if (realmAndNonce != null) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); // Set up the digest authentication with the required values DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realmAndNonce[0]); digestAuth.overrideParamter("nonce", realmAndNonce[1]); // Add the authentication header try { httpUriRequest.setHeader(digestAuth.authenticate(creds, httpUriRequest)); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } }
From source file:org.opencastproject.serviceregistry.api.RemoteBase.java
/** * Makes a request to all available remote services and returns the response as soon as the first of them returns the * expected http status code.//from w w w . j a va 2 s . c o m * * @param httpRequest * the http request. If the URI is specified, it should include only the path beyond the service endpoint. * For example, a request intended for http://{host}/{service}/extra/path/info.xml should include the URI * "/extra/path/info.xml". * @param expectedHttpStatus * any expected status codes to include in the return. * @return the response object, or null if we can not connect to any services */ protected HttpResponse getResponse(HttpRequestBase httpRequest, Integer... expectedHttpStatus) { boolean warnedUnavailability = false; // Try forever while (true) { List<ServiceRegistration> remoteServices = null; List<String> servicesInWarningState = new ArrayList<String>(); // Find available services while (remoteServices == null || remoteServices.size() == 0) { boolean warned = false; try { remoteServices = remoteServiceManager.getServiceRegistrationsByLoad(serviceType); if (remoteServices == null || remoteServices.size() == 0) { if (!warned) { logger.warn("No services of type '{}' found, waiting...", serviceType); warned = true; } logger.debug("Still no services of type '{}' found, waiting...", serviceType); try { Thread.sleep(TIMEOUT); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for remote service of type '{}'", serviceType); return null; } } } catch (ServiceRegistryException e) { logger.warn("Unable to obtain a list of remote services", e); return null; } } URI originalUri = httpRequest.getURI(); String uriSuffix = null; if (originalUri != null && StringUtils.isNotBlank(originalUri.toString())) { uriSuffix = originalUri.toString(); } // Try each available service for (ServiceRegistration remoteService : remoteServices) { HttpResponse response = null; try { String fullUrl = null; if (uriSuffix == null) { fullUrl = UrlSupport.concat(remoteService.getHost(), remoteService.getPath()); } else { fullUrl = UrlSupport.concat( new String[] { remoteService.getHost(), remoteService.getPath(), uriSuffix }); } logger.debug("Connecting to remote service of type '{}' at {}", serviceType, fullUrl); URI uri = new URI(fullUrl); httpRequest.setURI(uri); response = client.execute(httpRequest); StatusLine status = response.getStatusLine(); if (Arrays.asList(expectedHttpStatus).contains(status.getStatusCode())) { if (servicesInWarningState.contains(fullUrl)) { logger.warn("Service at {} is back to normal with expected status code {}", fullUrl, status.getStatusCode()); } return response; } else { if (!knownHttpStatuses.contains(status.getStatusCode()) && !servicesInWarningState.contains(fullUrl)) { logger.warn("Service at {} returned unexpected response code {}", fullUrl, status.getStatusCode()); servicesInWarningState.add(fullUrl); } closeConnection(response); } } catch (Exception e) { closeConnection(response); } } // Reset Original URI httpRequest.setURI(originalUri); // If none of them accepted the request, let's wait and retry if (!warnedUnavailability) { logger.warn("No service of type '{}' is currently readily available", serviceType); warnedUnavailability = true; } else { logger.debug("All services of type '{}' are still unavailable", serviceType); } try { Thread.sleep(TIMEOUT); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for remote service of type '{}'", serviceType); return null; } } }
From source file:org.openo.sdnhub.osdriverservice.openstack.client.http.OpenStackHttpConnection.java
private HttpResult commonRequest(HttpInput input, boolean fromLogin) throws OpenStackException { LOGGER.info("HTTP Request :" + input); if (!fromLogin) { if (this.credentials.getToken() == null) { this.login(); }//from w w w . j a va2 s . c o m input.setUri(this.getAbsoluteUrl(input.getContext(), input.getUri())); } this.addCommonHeaders(input); HttpRequestBase requestBase = null; if ("post".equals(input.getMethod())) { HttpPost httpPost = new HttpPost(); httpPost.setEntity(this.getStringEntity(input)); requestBase = httpPost; } else if ("put".equals(input.getMethod())) { HttpPut httpPut = new HttpPut(); httpPut.setEntity(this.getStringEntity(input)); requestBase = httpPut; } else if ("get".equals(input.getMethod())) { requestBase = new HttpGet(); } else if ("delete".equals(input.getMethod())) { requestBase = new HttpDelete(); } else { LOGGER.error("IllegalArgumentException failed. "); throw new IllegalArgumentException("Invalid HTTP method"); } requestBase.setURI(URI.create(input.getUri())); for (Entry<String, String> h : input.getReqHeaders().entrySet()) { requestBase.addHeader(h.getKey(), h.getValue()); } HttpResult result = new HttpResult(); try { HttpResponse resp = this.httpClient.execute(requestBase); String respContent = this.getResponseBody(resp); LOGGER.info("HTTP Request body: " + requestBase); result.setBody(respContent); result.setStatus(resp.getStatusLine().getStatusCode()); result.setRespHeaders(this.getHttpHeaders(resp)); } catch (ParseException | IOException e) { LOGGER.error("HTTP " + requestBase + " failed due to " + e.getMessage()); throw new OpenStackException(e); } finally { HttpGateKeeper.add(input, result); } LOGGER.info("HTTP Response" + result); return result; }