List of usage examples for org.apache.http.client.methods CloseableHttpResponse getAllHeaders
Header[] getAllHeaders();
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING)); String responseData = null;/* w ww .j a va2s . c o m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; boolean validateResponse = false; CloseableHttpClient client = null; HttpRequestBase httpMethod = null; CloseableHttpResponse httpResponse = null; File tempFile = null; int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000); try { configuration.configureDispatcher(this, httpDispatcherProperties); long dispatcherId = getDispatcherId(); client = clients.get(dispatcherId); if (client == null) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); if (httpDispatcherProperties.isUseProxyServer()) { clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner()); } client = clientBuilder.build(); clients.put(dispatcherId, client); } URI hostURI = new URI(httpDispatcherProperties.getHost()); String host = hostURI.getHost(); String scheme = hostURI.getScheme(); int port = hostURI.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Parse the content type field first, and then add the charset if needed ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType()); Charset charset = null; if (contentType.getCharset() == null) { charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset())); } else { charset = contentType.getCharset(); } if (httpDispatcherProperties.isMultipart()) { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); } HttpHost target = new HttpHost(host, port, scheme); httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile, contentType, charset); HttpClientContext context = HttpClientContext.create(); // authentication if (httpDispatcherProperties.isUseAuthentication()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(), httpDispatcherProperties.getPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create(); if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) { logger.debug("using Digest authentication"); registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { processDigestChallenge(authCache, target, credentials, httpMethod, context); } } else { logger.debug("using Basic authentication"); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { authCache.put(target, new BasicScheme()); } } context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); logger.debug("using authentication with credentials: " + credentials); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); // Set proxy information if (httpDispatcherProperties.isUseProxyServer()) { context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(), Integer.parseInt(httpDispatcherProperties.getProxyPort()))); } // execute the method logger.debug( "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString()); httpResponse = client.execute(target, httpMethod, context); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("received status code: " + statusCode); Map<String, List<String>> headers = new HashMap<String, List<String>>(); for (Header header : httpResponse.getAllHeaders()) { List<String> list = headers.get(header.getName()); if (list == null) { list = new ArrayList<String>(); headers.put(header.getName(), list); } list.add(header.getValue()); } connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString()); connectorMessage.getConnectorMap().put("responseHeaders", new MessageHeaders(new CaseInsensitiveMap(headers))); ContentType responseContentType = ContentType.get(httpResponse.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_PLAIN; } Charset responseCharset = charset; if (responseContentType.getCharset() != null) { responseCharset = responseContentType.getCharset(); } final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes(); BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() { @Override public boolean isBinaryContentType(ContentType contentType) { return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType); } }; /* * First parse out the body of the HTTP response. Depending on the connector settings, * this could end up being a string encoded with the response charset, a byte array * representing the raw response payload, or a MimeMultipart object. */ Object responseBody = ""; // The entity could be null in certain cases such as 204 responses if (httpResponse.getEntity() != null) { // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (httpDispatcherProperties.isResponseXmlBody() && httpDispatcherProperties.isResponseParseMultipart() && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) { responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), responseContentType.toString())); } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) { responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent()); } else { responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset); } } /* * Now that we have the response body, we need to create the actual Response message * data. Depending on the connector settings this could be our custom serialized XML, a * Base64 string encoded from the raw response payload, or a string encoded from the * payload with the request charset. */ if (httpDispatcherProperties.isResponseXmlBody()) { responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody, responseContentType, httpDispatcherProperties.isResponseParseMultipart(), httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver); } else if (responseBody instanceof byte[]) { responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII"); } else { responseData = (String) responseBody; } validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse(); if (statusCode < HttpStatus.SC_BAD_REQUEST) { responseStatus = Status.SENT; } else { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Received error response from HTTP server.", null)); responseStatusMessage = ErrorMessageBuilder .buildErrorResponse("Received error response from HTTP server.", null); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData, null); } } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error connecting to HTTP server.", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error connecting to HTTP server", e); } finally { try { HttpClientUtils.closeQuietly(httpResponse); // Delete temp files if we created them if (tempFile != null) { tempFile.delete(); tempFile = null; } } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }
From source file:org.artifactory.repo.HttpRepo.java
/** * Notice: for use with HEAD method, no content is expected in the response. * Process the remote repository's response and construct a repository resource. * * @param repoPath of requested resource * @param method executed {@link org.apache.http.client.methods.HttpHead} from which to process the response. * @param response The response to the get info request * @param context/* www. j a v a2s.c o m*/ * @param requestContext * @return */ protected RepoResource handleGetInfoResponse(RepoPath repoPath, HttpRequestBase method, CloseableHttpResponse response, @Nullable HttpClientContext context, RequestContext requestContext) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NOT_FOUND) { RepoRequests.logToContext( "Received status 404 (message: %s) on remote info request - returning unfound " + "resource", response.getStatusLine().getReasonPhrase()); return new UnfoundRepoResource(repoPath, response.getStatusLine().getReasonPhrase()); } if (!isDisableFolderRedirectAssertion(requestContext)) { assertNoRedirectToFolder(repoPath, context); } // Some servers may return 204 instead of 200 if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) { RepoRequests.logToContext( "Received status {} (message: %s) on remote info request - returning unfound " + "resource", statusCode, response.getStatusLine().getReasonPhrase()); // send back unfound resource with 404 status return new UnfoundRepoResource(repoPath, response.getStatusLine().getReasonPhrase()); } long lastModified = getLastModified(response); RepoRequests.logToContext("Found remote resource with last modified time - %s", new Date(lastModified).toString()); long contentLength = HttpUtils.getContentLength(response); if (contentLength != -1) { RepoRequests.logToContext("Found remote resource with content length - %s", contentLength); } // if status is 204 and length is not 0 then the remote server is doing something wrong if (statusCode == HttpStatus.SC_NO_CONTENT && contentLength > 0) { // send back unfound resource with 404 status RepoRequests.logToContext( "Received status {} (message: %s) on remote info request - returning unfound " + "resource", statusCode, response.getStatusLine().getReasonPhrase()); return new UnfoundRepoResource(repoPath, response.getStatusLine().getReasonPhrase()); } Set<ChecksumInfo> checksums = getChecksums(response); if (!checksums.isEmpty()) { RepoRequests.logToContext("Found remote resource with checksums - %s", checksums); } String originalPath = repoPath.getPath(); String filename = getFilename(method, originalPath); if (StringUtils.isNotBlank(filename)) { RepoRequests.logToContext("Found remote resource with filename header - %s", filename); if (NamingUtils.isMetadata(originalPath)) { String originalPathStrippedOfMetadata = NamingUtils.getMetadataParentPath(originalPath); String originalPathWithMetadataNameFromHeader = NamingUtils .getMetadataPath(originalPathStrippedOfMetadata, filename); repoPath = InternalRepoPathFactory.create(repoPath.getRepoKey(), originalPathWithMetadataNameFromHeader); } else { repoPath = InternalRepoPathFactory.create(repoPath.getParent(), filename); } } RepoRequests.logToContext("Returning found remote resource info"); RepoResource res = new RemoteRepoResource(repoPath, lastModified, contentLength, checksums, response.getAllHeaders()); return res; }
From source file:org.flowable.http.HttpActivityExecutor.java
public HttpResponse perform(CloseableHttpClient client, VariableContainer execution, final HttpRequest requestInfo, HttpRequestHandler httpRequestHandler, HttpResponseHandler httpResponseHandler, int socketTimeout, int connectTimeout, int connectionRequestTimeout) { HttpRequestBase request;/*from w w w . j ava 2 s . c o m*/ CloseableHttpResponse response = null; try { if (httpRequestHandler != null) { httpRequestHandler.handleHttpRequest(execution, requestInfo, client); } } catch (Exception e) { throw new FlowableException("Exception while invoking HttpRequestHandler: " + e.getMessage(), e); } try { URIBuilder uri = new URIBuilder(requestInfo.getUrl()); switch (requestInfo.getMethod()) { case "GET": { request = new HttpGet(uri.toString()); break; } case "POST": { HttpPost post = new HttpPost(uri.toString()); if (requestInfo.getBody() != null) { post.setEntity(new StringEntity(requestInfo.getBody())); } request = post; break; } case "PUT": { HttpPut put = new HttpPut(uri.toString()); put.setEntity(new StringEntity(requestInfo.getBody())); request = put; break; } case "DELETE": { request = new HttpDelete(uri.toString()); break; } default: { throw new FlowableException(requestInfo.getMethod() + " HTTP method not supported"); } } if (requestInfo.getHeaders() != null) { setHeaders(request, requestInfo.getHeaders()); } setConfig(request, requestInfo, socketTimeout, connectTimeout, connectionRequestTimeout); if (requestInfo.getTimeout() > 0) { timer.schedule(new TimeoutTask(request), requestInfo.getTimeout()); } response = client.execute(request); HttpResponse responseInfo = new HttpResponse(); if (response.getStatusLine() != null) { responseInfo.setStatusCode(response.getStatusLine().getStatusCode()); responseInfo.setProtocol(response.getStatusLine().getProtocolVersion().toString()); responseInfo.setReason(response.getStatusLine().getReasonPhrase()); } if (response.getAllHeaders() != null) { responseInfo.setHeaders(getHeadersAsString(response.getAllHeaders())); } if (response.getEntity() != null) { responseInfo.setBody(EntityUtils.toString(response.getEntity())); } try { if (httpResponseHandler != null) { httpResponseHandler.handleHttpResponse(execution, responseInfo); } } catch (Exception e) { throw new FlowableException("Exception while invoking HttpResponseHandler: " + e.getMessage(), e); } return responseInfo; } catch (final ClientProtocolException e) { throw new FlowableException("HTTP exception occurred", e); } catch (final IOException e) { throw new FlowableException("IO exception occurred", e); } catch (final URISyntaxException e) { throw new FlowableException("Invalid URL exception occurred", e); } finally { if (response != null) { try { response.close(); } catch (Throwable e) { LOGGER.error("Could not close http response", e); } } } }
From source file:org.flowable.http.impl.HttpActivityBehaviorImpl.java
@Override public HttpResponse perform(final DelegateExecution execution, final HttpRequest requestInfo) { HttpRequestBase request = null;//from w ww. j ava 2 s . c o m CloseableHttpResponse response = null; ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil .getProcessEngineConfiguration(); try { if (httpServiceTask.getHttpRequestHandler() != null) { HttpRequestHandler httpRequestHandler = createHttpRequestHandler( httpServiceTask.getHttpRequestHandler(), processEngineConfiguration); httpRequestHandler.handleHttpRequest(execution, requestInfo, client); } } catch (Exception e) { throw new FlowableException("Exception while invoking HttpRequestHandler: " + e.getMessage(), e); } try { URIBuilder uri = new URIBuilder(requestInfo.getUrl()); switch (requestInfo.getMethod()) { case "GET": { request = new HttpGet(uri.toString()); break; } case "POST": { HttpPost post = new HttpPost(uri.toString()); post.setEntity(new StringEntity(requestInfo.getBody())); request = post; break; } case "PUT": { HttpPut put = new HttpPut(uri.toString()); put.setEntity(new StringEntity(requestInfo.getBody())); request = put; break; } case "DELETE": { HttpDelete delete = new HttpDelete(uri.toString()); request = delete; break; } default: { throw new FlowableException(requestInfo.getMethod() + " HTTP method not supported"); } } if (requestInfo.getHeaders() != null) { setHeaders(request, requestInfo.getHeaders()); } setConfig(request, requestInfo, CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig()); if (requestInfo.getTimeout() > 0) { timer.schedule(new TimeoutTask(request), requestInfo.getTimeout()); } response = client.execute(request); HttpResponse responseInfo = new HttpResponse(); if (response.getStatusLine() != null) { responseInfo.setStatusCode(response.getStatusLine().getStatusCode()); responseInfo.setProtocol(response.getStatusLine().getProtocolVersion().toString()); responseInfo.setReason(response.getStatusLine().getReasonPhrase()); } if (response.getAllHeaders() != null) { responseInfo.setHeaders(getHeadersAsString(response.getAllHeaders())); } if (response.getEntity() != null) { responseInfo.setBody(EntityUtils.toString(response.getEntity())); } try { if (httpServiceTask.getHttpResponseHandler() != null) { HttpResponseHandler httpResponseHandler = createHttpResponseHandler( httpServiceTask.getHttpResponseHandler(), processEngineConfiguration); httpResponseHandler.handleHttpResponse(execution, responseInfo); } } catch (Exception e) { throw new FlowableException("Exception while invoking HttpResponseHandler: " + e.getMessage(), e); } return responseInfo; } catch (final ClientProtocolException e) { throw new FlowableException("HTTP exception occurred", e); } catch (final IOException e) { throw new FlowableException("IO exception occurred", e); } catch (final URISyntaxException e) { throw new FlowableException("Invalid URL exception occurred", e); } catch (final FlowableException e) { throw e; } finally { if (response != null) { try { response.close(); } catch (Throwable e) { LOGGER.error("Could not close http response", e); } } } }
From source file:org.roda.core.common.SeleniumUtils.java
private static void sendPostRequest(String source) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("input", source); HttpPost httpPost = new HttpPost("http://www.acessibilidade.gov.pt/accessmonitor/"); httpPost.setEntity(builder.build()); try {// ww w . ja v a 2 s . c om CloseableHttpResponse response = httpClient.execute(httpPost); System.err.println(response); for (Header h : response.getAllHeaders()) { if ("location".equalsIgnoreCase(h.getName())) { locations.put(h.getValue(), driver.getCurrentUrl()); } } } catch (IOException e) { System.err.println("Error sending POST request!"); } }
From source file:org.structr.rest.common.HttpHelper.java
public static Map<String, String> head(final String address, final String username, final String password, final String proxyUrl, final String proxyUsername, final String proxyPassword, final String cookie, final Map<String, String> headers) { final Map<String, String> responseHeaders = new HashMap<>(); try {/*from w w w.j a va 2s. c o m*/ final URI url = URI.create(address); final HttpHead req = new HttpHead(url); configure(req, username, password, proxyUrl, proxyUsername, proxyPassword, cookie, headers, false); final CloseableHttpResponse response = client.execute(req); responseHeaders.put("status", Integer.toString(response.getStatusLine().getStatusCode())); for (final Header header : response.getAllHeaders()) { responseHeaders.put(header.getName(), header.getValue()); } } catch (final Throwable t) { logger.error("Unable to get headers from address {}, {}", new Object[] { address, t.getMessage() }); } return responseHeaders; }
From source file:org.structr.rest.common.HttpHelper.java
public static Map<String, String> post(final String address, final String requestBody, final String username, final String password, final String proxyUrl, final String proxyUsername, final String proxyPassword, final String cookie, final Map<String, String> headers, final String charset) { final Map<String, String> responseData = new HashMap<>(); try {/* w ww . j av a 2s. co m*/ final URI url = URI.create(address); final HttpPost req = new HttpPost(url); configure(req, username, password, proxyUrl, proxyUsername, proxyPassword, cookie, headers, true); req.setEntity(new StringEntity(requestBody, charset)); final CloseableHttpResponse response = client.execute(req); String content = IOUtils.toString(response.getEntity().getContent(), charset(response)); content = skipBOMIfPresent(content); responseData.put("body", content); responseData.put("status", Integer.toString(response.getStatusLine().getStatusCode())); for (final Header header : response.getAllHeaders()) { responseData.put(header.getName(), header.getValue()); } } catch (final Throwable t) { logger.error("Unable to fetch content from address {}, {}", new Object[] { address, t.getMessage() }); } return responseData; }
From source file:org.structr.rest.common.HttpHelper.java
public static Map<String, String> put(final String address, final String requestBody, final String username, final String password, final String proxyUrl, final String proxyUsername, final String proxyPassword, final String cookie, final Map<String, String> headers, final String charset) { final Map<String, String> responseData = new HashMap<>(); try {/*ww w . j ava 2 s . c om*/ final URI url = URI.create(address); final HttpPut req = new HttpPut(url); configure(req, username, password, proxyUrl, proxyUsername, proxyPassword, cookie, headers, true); req.setEntity(new StringEntity(requestBody, charset)); final CloseableHttpResponse response = client.execute(req); String content = IOUtils.toString(response.getEntity().getContent(), charset(response)); content = skipBOMIfPresent(content); responseData.put("body", content); responseData.put("status", Integer.toString(response.getStatusLine().getStatusCode())); for (final Header header : response.getAllHeaders()) { responseData.put(header.getName(), header.getValue()); } } catch (final Throwable t) { logger.error("Unable to fetch content from address {}, {}", new Object[] { address, t.getMessage() }); } return responseData; }
From source file:org.structr.rest.common.HttpHelper.java
public static Map<String, String> delete(final String address, final String username, final String password, final String proxyUrl, final String proxyUsername, final String proxyPassword, final String cookie, final Map<String, String> headers) { final Map<String, String> responseData = new HashMap<>(); try {/* www .j a v a 2s . c o m*/ final URI url = URI.create(address); final HttpDelete req = new HttpDelete(url); configure(req, username, password, proxyUrl, proxyUsername, proxyPassword, cookie, headers, true); final CloseableHttpResponse response = client.execute(req); String content = IOUtils.toString(response.getEntity().getContent(), charset(response)); content = skipBOMIfPresent(content); responseData.put("body", content); responseData.put("status", Integer.toString(response.getStatusLine().getStatusCode())); for (final Header header : response.getAllHeaders()) { responseData.put(header.getName(), header.getValue()); } } catch (final Throwable t) { logger.error("Unable to issue DELETE command to address {}, {}", new Object[] { address, t.getMessage() }); } return responseData; }