List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java
/** * Execute the given request, without using the response body. In case the response returns a different status-code than expected, an {@link FlowableServiceException} is thrown with the error * message received from the client, if possible. *//*from w w w .jav a 2s. c om*/ public void executeRequestNoResponseBody(HttpUriRequest request, ServerConfig serverConfig, int expectedStatusCode) { FlowableServiceException exception = null; CloseableHttpClient client = getHttpClient(serverConfig); try { CloseableHttpResponse response = client.execute(request); boolean success = response.getStatusLine() != null && response.getStatusLine().getStatusCode() == expectedStatusCode; if (!success) { String errorMessage = null; try { if (response.getEntity() != null && response.getEntity().getContentLength() != 0) { InputStream responseContent = response.getEntity().getContent(); JsonNode errorBody = objectMapper.readTree(responseContent); errorMessage = extractError(errorBody, "An error occurred while calling Flowable: " + response.getStatusLine()); } else { errorMessage = "An error was returned when calling the Flowable server"; } } catch (Exception e) { LOGGER.warn("Error consuming response from uri {}", request.getURI(), e); exception = wrapException(e, request); } finally { response.close(); } exception = new FlowableServiceException(errorMessage); } } catch (Exception e) { LOGGER.error("Error executing request to uri {}", request.getURI(), e); exception = wrapException(e, request); } finally { try { client.close(); } catch (Exception e) { // No need to throw upwards, as this may hide exceptions/valid result LOGGER.warn("Error closing http client instance", e); } } if (exception != null) { throw exception; } }
From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java
/** * @return {@link T}/* ww w . jav a 2 s .co m*/ * @throws Exception */ @Override public T getResponse() throws Exception { HttpUriRequest httpMethod = this.prepareHttpMethod(); httpMethod.addHeader("Content-Type", "application/json"); logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString()); CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode, this.getClass().getSimpleName()); this.checkHttpResponseStatus(statusCode); HttpEntity responseEntity = httpResponse.getEntity(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(responseEntity.getContent(), UTF_8_CHARSERT))) { return readInternal(reader); } catch (Exception ex) { throw new IncorrectResponseException(ex); } finally { consume(responseEntity); httpResponse.close(); } }
From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java
/** * <p>/* w w w . j a va 2 s .co m*/ * Method to generate Response AS a {@link String} value. * </p> * * @return {@link String} * @throws Exception */ @Override public String getResponseAsString() throws Exception { HttpUriRequest httpMethod = this.prepareHttpMethod(); httpMethod.addHeader("Content-Type", "application/json"); logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString()); CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode, this.getClass().getSimpleName()); this.checkHttpResponseStatus(statusCode); HttpEntity responseEntity = httpResponse.getEntity(); try { if (responseEntity != null) { return CharStreams.toString(new InputStreamReader(responseEntity.getContent(), UTF_8)); } else { throw new IncorrectResponseException(CONNECTION_PROBLEM_MESSAGE); } } finally { consume(responseEntity); httpResponse.close(); } }
From source file:org.geosdi.geoplatform.connector.server.request.json.GPBaseJsonConnectorRequest.java
/** * <p>/* w w w. ja va2 s . co m*/ * Method to generate Response AS a {@link InputStream} Stream. Remember to * close the Stream</p> * * @return {@link InputStream} stream * @throws Exception */ @Override public InputStream getResponseAsStream() throws Exception { HttpUriRequest httpMethod = this.prepareHttpMethod(); httpMethod.addHeader("Content-Type", "application/json"); logger.debug("#############################Executing -------------> {}\n", httpMethod.getURI().toString()); CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpMethod); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("###############################STATUS_CODE : {} for Request : {}\n", statusCode, this.getClass().getSimpleName()); this.checkHttpResponseStatus(statusCode); HttpEntity responseEntity = httpResponse.getEntity(); try { if (responseEntity != null) { InputStream inputStream = responseEntity.getContent(); return new ByteArrayInputStream(IOUtils.toByteArray(inputStream)); } else { throw new IncorrectResponseException(CONNECTION_PROBLEM_MESSAGE); } } finally { consume(responseEntity); httpResponse.close(); } }
From source file:org.jenkinsci.plugins.GithubSecurityRealm.java
/** * Returns the proxy to be used when connecting to the given URI. *//*from www . j a v a 2 s. c om*/ private HttpHost getProxy(HttpUriRequest method) throws URIException { ProxyConfiguration proxy = Jenkins.getInstance().proxy; if (proxy == null) return null; // defensive check Proxy p = proxy.createProxy(method.getURI().getHost()); switch (p.type()) { case DIRECT: return null; // no proxy case HTTP: InetSocketAddress sa = (InetSocketAddress) p.address(); return new HttpHost(sa.getHostName(), sa.getPort()); case SOCKS: default: return null; // not supported yet } }
From source file:org.mule.modules.quickbooks.api.AbstractQuickBooksClientOAuth.java
@SuppressWarnings("ThrowFromFinallyBlock") protected Object makeARequestToQuickbooks(HttpUriRequest httpRequest, OAuthCredentials credentials, boolean rawResponse) { CommonsHttpOAuthConsumer postConsumer = new CommonsHttpOAuthConsumer(getConsumerKey(), getConsumerSecret()); postConsumer.setMessageSigner(new HmacSha1MessageSigner()); postConsumer.setTokenWithSecret(credentials.getAccessToken(), credentials.getAccessTokenSecret()); try {/*from ww w . ja v a 2 s . com*/ if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("## Signing HttpRequest: %s", httpRequest.getURI().toString())); } postConsumer.sign(httpRequest); } catch (Exception e) { throw MuleSoftException.soften(e); } BufferedReader br = null; StringBuffer responseBody = null; HttpResponse response; int statusCode; try { response = client.execute(httpRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String readLine; responseBody = new StringBuffer(); while ((readLine = br.readLine()) != null) { responseBody.append(readLine).append(System.getProperty("line.separator")); } statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ExceptionInfo fault = getFaultInfo(responseBody.toString()); throw new QuickBooksRuntimeException(fault); } } catch (Exception e) { throw MuleSoftException.soften(e); } finally { if (br != null) { try { br.close(); } catch (Exception e) { throw MuleSoftException.soften(e); } } } try { if (rawResponse) return responseBody.toString(); return getMessageUtilsInstance().parseResponse(responseBody.toString()); } catch (JAXBException e) { throw MuleSoftException.soften(e); } }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
/** * Retries a request if the nonce timed out during the request. * /* www . j a v a 2 s.c o m*/ * @param httpUriRequest * The request to be made that isn't a GET, those are handled automatically. * @param response * The response with the bad nonce timeout in it. * @return A new response for the request if it was successful without the nonce timing out again or just the same * response it got if it ran out of attempts. * @throws TrustedHttpClientException * @throws IOException * @throws ClientProtocolException */ private HttpResponse retryAuthAndRequestAfterNonceTimeout(HttpUriRequest httpUriRequest, HttpResponse response) throws TrustedHttpClientException, IOException, ClientProtocolException { // Get rid of old security headers with the old nonce. httpUriRequest.removeHeaders(AUTHORIZATION_HEADER_NAME); for (int i = 0; i < nonceTimeoutRetries; i++) { HttpClient httpClient = makeHttpClient(); int variableDelay = 0; // Make sure that we have a variable delay greater than 0. if (retryMaximumVariableTime > 0) { variableDelay = generator.nextInt(retryMaximumVariableTime * MILLISECONDS_IN_SECONDS); } long totalDelay = (retryBaseDelay * MILLISECONDS_IN_SECONDS + variableDelay); if (totalDelay > 0) { logger.info("Sleeping " + totalDelay + "ms before trying request " + httpUriRequest.getURI() + " again due to a " + response.getStatusLine()); try { Thread.sleep(totalDelay); } catch (InterruptedException e) { logger.error("Suffered InteruptedException while trying to sleep until next retry.", e); } } manuallyHandleDigestAuthentication(httpUriRequest, httpClient); response = httpClient.execute(httpUriRequest); if (!hadNonceTimeoutResponse(response)) { responseMap.put(response, httpClient); break; } httpClient.getConnectionManager().shutdown(); } return 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. j a v a 2 s. c om * @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.opendatakit.briefcase.util.AggregateUtils.java
/** * Common method for returning a parsed xml document given a url and the http * context and client objects involved in the web connection. The document is * the body of the response entity and should be xml. * /*from ww w .ja v a 2 s. c o m*/ * @param urlString * @param localContext * @param httpclient * @return */ private static final DocumentFetchResult httpRetrieveXmlDocument(HttpUriRequest request, int[] validStatusList, ServerConnectionInfo serverInfo, boolean alwaysResetCredentials, DocumentDescription description, ResponseAction action) throws XmlDocumentFetchException { HttpClient httpClient = WebUtils.createHttpClient(); // get shared HttpContext so that authentication and cookies are retained. HttpClientContext localContext = WebUtils.getHttpContext(); URI uri = request.getURI(); WebUtils.setCredentials(localContext, serverInfo, uri, alwaysResetCredentials); if (description.isCancelled()) { throw new XmlDocumentFetchException( "Transfer of " + description.getDocumentDescriptionType() + " aborted."); } HttpResponse response = null; try { response = httpClient.execute(request, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String lcContentType = (entity == null) ? null : entity.getContentType().getValue().toLowerCase(); XmlDocumentFetchException ex = null; boolean statusCodeValid = false; for (int i : validStatusList) { if (i == statusCode) { statusCodeValid = true; break; } } // if anything is amiss, ex will be non-null after this cascade. if (!statusCodeValid) { String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; if (statusCode == 400) { ex = new XmlDocumentFetchException(description.getFetchDocFailed() + webError + " while accessing: " + uri.toString() + "\nPlease verify that the " + description.getDocumentDescriptionType() + " that is being uploaded is well-formed."); } else { ex = new XmlDocumentFetchException(description.getFetchDocFailed() + webError + " while accessing: " + uri.toString() + "\nPlease verify that the URL, your user credentials and your permissions are all correct."); } } else if (entity == null) { log.warn("No entity body returned from: " + uri.toString() + " is not text/xml"); ex = new XmlDocumentFetchException(description.getFetchDocFailed() + " Server unexpectedly returned no content while accessing: " + uri.toString()); } else if (!(lcContentType.contains(HTTP_CONTENT_TYPE_TEXT_XML) || lcContentType.contains(HTTP_CONTENT_TYPE_APPLICATION_XML))) { log.warn("ContentType: " + entity.getContentType().getValue() + "returned from: " + uri.toString() + " is not text/xml"); ex = new XmlDocumentFetchException(description.getFetchDocFailed() + "A non-XML document was returned while accessing: " + uri.toString() + "\nA network login screen may be interfering with the transmission to the server."); } if (ex != null) { flushEntityBytes(entity); // and throw the exception... throw ex; } // parse the xml document... Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { log.warn("Parsing failed with " + e.getMessage(), e); throw new XmlDocumentFetchException( description.getFetchDocFailed() + " while accessing: " + uri.toString()); } // examine header fields... // is it an OpenRosa server? boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { log.warn(WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b); } } // what about location? Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(locations[0].getValue()); URI uNew = url.toURI(); if (uri.getHost().equalsIgnoreCase(uNew.getHost())) { // trust the server to tell us a new location // ... and possibly to use https instead. String fullUrl = url.toExternalForm(); int idx = fullUrl.lastIndexOf("/"); serverInfo.setUrl(fullUrl.substring(0, idx)); } else { // Don't follow a redirection attempt to a different host. // We can't tell if this is a spoof or not. String msg = description.getFetchDocFailed() + "Unexpected redirection attempt to a different host: " + uNew.toString(); log.warn(msg); throw new XmlDocumentFetchException(msg); } } catch (MalformedURLException | URISyntaxException e) { String msg = description.getFetchDocFailed() + "Unexpected exception: " + e.getMessage(); log.warn(msg, e); throw new XmlDocumentFetchException(msg); } } DocumentFetchResult result = new DocumentFetchResult(doc, isOR); if (action != null) { action.doAction(result); } return result; } catch (UnknownHostException e) { String msg = description.getFetchDocFailed() + "Unknown host: " + e.getMessage(); log.warn(msg, e); throw new XmlDocumentFetchException(msg); } catch (IOException | MetadataUpdateException e) { String msg = description.getFetchDocFailed() + "Unexpected exception: " + e; log.warn(msg, e); throw new XmlDocumentFetchException(msg); } }
From source file:org.pixmob.droidlink.net.NetworkClient.java
public HttpResponse execute(HttpUriRequest request) throws IOException, AppEngineAuthenticationException { HttpResponse resp = null;// w ww . java 2 s . c om try { resp = client.execute(request); final int statusCode = resp.getStatusLine().getStatusCode(); if (DEVELOPER_MODE) { Log.i(TAG, "Result for request " + request.getURI().toASCIIString() + ": " + statusCode); } return resp; } catch (AppEngineAuthenticationException e) { closeResources(request, resp); throw e; } catch (IOException e) { closeResources(request, resp); throw e; } }