Java Code Examples for org.eclipse.jetty.client.api.ContentResponse#getContent()
The following examples show how to use
org.eclipse.jetty.client.api.ContentResponse#getContent() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JettyXhrTransport.java From spring-analysis-note with MIT License | 6 votes |
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, @Nullable String body) { Request httpRequest = this.httpClient.newRequest(url).method(method); addHttpHeaders(httpRequest, headers); if (body != null) { httpRequest.content(new StringContentProvider(body)); } ContentResponse response; try { response = httpRequest.send(); } catch (Exception ex) { throw new SockJsTransportFailureException("Failed to execute request to " + url, ex); } HttpStatus status = HttpStatus.valueOf(response.getStatus()); HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders()); return (response.getContent() != null ? new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) : new ResponseEntity<>(responseHeaders, status)); }
Example 2
Source File: JettyXhrTransport.java From java-technology-stack with MIT License | 6 votes |
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, @Nullable String body) { Request httpRequest = this.httpClient.newRequest(url).method(method); addHttpHeaders(httpRequest, headers); if (body != null) { httpRequest.content(new StringContentProvider(body)); } ContentResponse response; try { response = httpRequest.send(); } catch (Exception ex) { throw new SockJsTransportFailureException("Failed to execute request to " + url, ex); } HttpStatus status = HttpStatus.valueOf(response.getStatus()); HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders()); return (response.getContent() != null ? new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) : new ResponseEntity<>(responseHeaders, status)); }
Example 3
Source File: ProtobufRpcCallExceptionDecoder.java From ja-micro with Apache License 2.0 | 6 votes |
@Override public RpcCallException decodeException(ContentResponse response) throws RpcCallException { try { if (response != null) { byte[] data = response.getContent(); if (ArrayUtils.isEmpty(data)) { logger.warn("Unable to decode: empty response received"); return new RpcCallException(RpcCallException.Category.InternalServerError, "Empty response received"); } ProtobufRpcResponse pbResponse = new ProtobufRpcResponse(data); String error = pbResponse.getErrorMessage(); if (error != null) { return RpcCallException.fromJson(error); } } } catch (Exception ex) { logger.warn("Caught exception decoding protobuf response exception", ex); throw new RpcCallException(RpcCallException.Category.InternalServerError, RpcCallExceptionDecoder.exceptionToString(ex)); } return null; }
Example 4
Source File: RpcClient.java From ja-micro with Apache License 2.0 | 6 votes |
public RESPONSE callSynchronous(Message request, OrangeContext orangeContext) throws RpcCallException { HttpClientWrapper clientWrapper = loadBalancer.getHttpClientWrapper(); HttpRequestWrapper balancedPost = clientWrapper.createHttpPost(this); //set custom headers if (orangeContext != null) { orangeContext.getProperties().forEach(balancedPost::setHeader); } balancedPost.setHeader("Content-type", TYPE_OCTET); //TODO: fix: Temporary workaround below until go services are more http compliant balancedPost.setHeader("Connection", "close"); ProtobufRpcRequest pbRequest = new ProtobufRpcRequest(methodName, request); byte[] protobufData = pbRequest.getProtobufData(); balancedPost.setContentProvider(new BytesContentProvider(protobufData)); logger.debug("Sending request of size {}", protobufData.length); ContentResponse rpcResponse = clientWrapper.execute(balancedPost, new ProtobufRpcCallExceptionDecoder(), orangeContext); byte[] data = rpcResponse.getContent(); logger.debug("Received a proto response of size: {}", data.length); return ProtobufUtil.byteArrayToProtobuf( new ProtobufRpcResponse(data).getPayloadData(), responseClass); }
Example 5
Source File: JettyXhrTransport.java From spring4-understanding with Apache License 2.0 | 6 votes |
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, String body) { Request httpRequest = this.httpClient.newRequest(url).method(method); addHttpHeaders(httpRequest, headers); if (body != null) { httpRequest.content(new StringContentProvider(body)); } ContentResponse response; try { response = httpRequest.send(); } catch (Exception ex) { throw new SockJsTransportFailureException("Failed to execute request to " + url, ex); } HttpStatus status = HttpStatus.valueOf(response.getStatus()); HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders()); return (response.getContent() != null ? new ResponseEntity<String>(response.getContentAsString(), responseHeaders, status) : new ResponseEntity<String>(responseHeaders, status)); }
Example 6
Source File: HttpClientWrapper.java From ja-micro with Apache License 2.0 | 5 votes |
private boolean responseWasSuccessful(RpcCallExceptionDecoder decoder, ContentResponse response, int lastStatusCode) throws RpcCallException { if (shouldExposeErrorsToHttp(serviceProps)) { return lastStatusCode == 200 && response != null && response.getContent().length > 0; } else if (lastStatusCode != 0 && lastStatusCode != 200) { return false; } else if (response == null || response.getContent() == null) { return false; } RpcCallException exception = decoder.decodeException(response); return (exception == null); }
Example 7
Source File: DataTest.java From app-runner with MIT License | 5 votes |
private static List<String> getFilesInZip(ContentResponse resp) throws IOException { byte[] content = resp.getContent(); List<String> pathsInZip = new ArrayList<>(); try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content))) { ZipEntry nextEntry; while ((nextEntry = zis.getNextEntry()) != null) { pathsInZip.add(nextEntry.getName()); } } return pathsInZip; }
Example 8
Source File: CcuGateway.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Main method for sending a TclRega script and parsing the XML result. */ @SuppressWarnings("unchecked") private synchronized <T> T sendScript(String script, Class<T> clazz) throws IOException { try { script = StringUtils.trim(script); if (StringUtils.isEmpty(script)) { throw new RuntimeException("Homematic TclRegaScript is empty!"); } if (logger.isTraceEnabled()) { logger.trace("TclRegaScript: {}", script); } StringContentProvider content = new StringContentProvider(script, config.getEncoding()); ContentResponse response = httpClient.POST(config.getTclRegaUrl()).content(content) .timeout(config.getTimeout(), TimeUnit.SECONDS) .header(HttpHeader.CONTENT_TYPE, "text/plain;charset=" + config.getEncoding()).send(); String result = new String(response.getContent(), config.getEncoding()); result = StringUtils.substringBeforeLast(result, "<xml><exec>"); if (logger.isTraceEnabled()) { logger.trace("Result TclRegaScript: {}", result); } return (T) xStream.fromXML(result); } catch (Exception ex) { throw new IOException(ex.getMessage(), ex); } }
Example 9
Source File: HttpUtil.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * * @param httpMethod the HTTP method to use * @param url the url to execute * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be sent to the given <code>url</code> or <code>null</code> if no content * should be sent. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout in milliseconds to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong * @throws IOException when the request execution failed, timed out or it was interrupted */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) throws IOException { ContentResponse response = executeUrlAndGetReponse(httpMethod, url, httpHeaders, content, contentType, timeout, proxyHost, proxyPort, proxyUser, proxyPassword, nonProxyHosts); String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim() : StandardCharsets.UTF_8.name(); String responseBody; try { responseBody = new String(response.getContent(), encoding); } catch (UnsupportedEncodingException e) { responseBody = null; } return responseBody; }
Example 10
Source File: HttpUtil.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
/** * Download the data from an URL. * * @param url the URL of the data to be downloaded * @param contentTypeRegex the REGEX the content type must match; null to ignore the content type * @param scanTypeInContent true to allow the scan of data to determine the content type if not found in the headers * @param maxContentLength the maximum data size in bytes to trigger the download; any negative value to ignore the * data size * @param timeout the socket timeout in milliseconds to wait for data * @return a RawType object containing the downloaded data, null if the content type does not match the expected * type or the data size is too big */ public static RawType downloadData(String url, String contentTypeRegex, boolean scanTypeInContent, long maxContentLength, int timeout) { final ProxyParams proxyParams = prepareProxyParams(); RawType rawData = null; try { ContentResponse response = executeUrlAndGetReponse("GET", url, null, null, null, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); byte[] data = response.getContent(); if (data == null) { data = new byte[0]; } long length = data.length; String mediaType = response.getMediaType(); LOGGER.debug("Media download response: status {} content length {} media type {} (URL {})", response.getStatus(), length, mediaType, url); if (response.getStatus() != HttpStatus.OK_200 || length == 0) { LOGGER.debug("Media download failed: unexpected return code {} (URL {})", response.getStatus(), url); return null; } if (maxContentLength >= 0 && length > maxContentLength) { LOGGER.debug("Media download aborted: content length {} too big (URL {})", length, url); return null; } String contentType = mediaType; if (contentTypeRegex != null) { if ((contentType == null || contentType.isEmpty()) && scanTypeInContent) { // We try to get the type from the data contentType = guessContentTypeFromData(data); LOGGER.debug("Media download: content type from data: {} (URL {})", contentType, url); } if (contentType != null && contentType.isEmpty()) { contentType = null; } if (contentType == null) { LOGGER.debug("Media download aborted: unknown content type (URL {})", url); return null; } else if (!contentType.matches(contentTypeRegex)) { LOGGER.debug("Media download aborted: unexpected content type \"{}\" (URL {})", contentType, url); return null; } } else if (contentType == null || contentType.isEmpty()) { contentType = RawType.DEFAULT_MIME_TYPE; } rawData = new RawType(data, contentType); LOGGER.debug("Media downloaded: size {} type {} (URL {})", rawData.getBytes().length, rawData.getMimeType(), url); } catch (IOException e) { LOGGER.debug("Media download failed (URL {}) : {}", url, e.getMessage()); } return rawData; }
Example 11
Source File: HttpCallOperatorFactory.java From digdag with Apache License 2.0 | 4 votes |
@Override public TaskResult runTask() { UserSecretTemplate uriTemplate = UserSecretTemplate.of(params.get("_command", String.class)); boolean uriIsSecret = uriTemplate.containsSecrets(); URI uri = URI.create(uriTemplate.format(context.getSecrets())); String mediaTypeOverride = params.getOptional("content_type_override", String.class).orNull(); ContentResponse response; HttpClient httpClient = client(); try { response = runHttp(httpClient, uri, uriIsSecret); } finally { stop(httpClient); } String content; if (Strings.isNullOrEmpty(mediaTypeOverride)) { // This ContentResponse::getContentAsString considers ;charset= parameter // of Content-Type. If not set, it uses UTF-8. content = response.getContentAsString(); } else { // This logic mimics how org.eclipse.jetty.client.HttpContentResponse::getContentAsString handles Content-Type int index = mediaTypeOverride.toLowerCase(ENGLISH).indexOf("charset="); if (index > 0) { String encoding = mediaTypeOverride.substring(index + "charset=".length()); try { content = new String(response.getContent(), encoding); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(encoding); } } else { content = new String(response.getContent(), UTF_8); } } // validate response length if (content.length() > maxResponseContentSize) { throw new TaskExecutionException("Response content too large: " + content.length() + " > " + maxResponseContentSize); } // parse content based on response media type String digFileSource = reformatDigFile(content, response.getMediaType(), mediaTypeOverride); // write to http_call.dig file Path workflowPath = writeDigFile(digFileSource); // following code is almost same with CallOperatorFactory.CallOperator.runTask Config config = request.getConfig(); WorkflowFile workflowFile; try { workflowFile = projectLoader.loadWorkflowFileFromPath( workspace.getProjectPath(), workflowPath, config.getFactory().create()); } catch (IOException ex) { throw propagateIoException(ex, WORKFLOW_FILE_NAME, ConfigException::new); } Config def = workflowFile.toWorkflowDefinition().getConfig(); return TaskResult.defaultBuilder(request) .subtaskConfig(def) .build(); }
Example 12
Source File: HttpUtil.java From smarthome with Eclipse Public License 2.0 | 4 votes |
/** * Download the data from an URL. * * @param url the URL of the data to be downloaded * @param contentTypeRegex the REGEX the content type must match; null to ignore the content type * @param scanTypeInContent true to allow the scan of data to determine the content type if not found in the headers * @param maxContentLength the maximum data size in bytes to trigger the download; any negative value to ignore the * data size * @param timeout the socket timeout in milliseconds to wait for data * @return a RawType object containing the downloaded data, null if the content type does not match the expected * type or the data size is too big */ public static RawType downloadData(String url, String contentTypeRegex, boolean scanTypeInContent, long maxContentLength, int timeout) { final ProxyParams proxyParams = prepareProxyParams(); RawType rawData = null; try { ContentResponse response = executeUrlAndGetReponse("GET", url, null, null, null, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); byte[] data = response.getContent(); if (data == null) { data = new byte[0]; } long length = data.length; String mediaType = response.getMediaType(); LOGGER.debug("Media download response: status {} content length {} media type {} (URL {})", response.getStatus(), length, mediaType, url); if (response.getStatus() != HttpStatus.OK_200 || length == 0) { LOGGER.debug("Media download failed: unexpected return code {} (URL {})", response.getStatus(), url); return null; } if (maxContentLength >= 0 && length > maxContentLength) { LOGGER.debug("Media download aborted: content length {} too big (URL {})", length, url); return null; } String contentType = mediaType; if (contentTypeRegex != null) { if ((contentType == null || contentType.isEmpty()) && scanTypeInContent) { // We try to get the type from the data contentType = guessContentTypeFromData(data); LOGGER.debug("Media download: content type from data: {} (URL {})", contentType, url); } if (contentType != null && contentType.isEmpty()) { contentType = null; } if (contentType == null) { LOGGER.debug("Media download aborted: unknown content type (URL {})", url); return null; } else if (!contentType.matches(contentTypeRegex)) { LOGGER.debug("Media download aborted: unexpected content type \"{}\" (URL {})", contentType, url); return null; } } else if (contentType == null || contentType.isEmpty()) { contentType = RawType.DEFAULT_MIME_TYPE; } rawData = new RawType(data, contentType); LOGGER.debug("Media downloaded: size {} type {} (URL {})", rawData.getBytes().length, rawData.getMimeType(), url); } catch (IOException e) { LOGGER.debug("Media download failed (URL {}) : {}", url, e.getMessage()); } return rawData; }
Example 13
Source File: HttpUtil.java From smarthome with Eclipse Public License 2.0 | 3 votes |
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * * @param httpMethod the HTTP method to use * @param url the url to execute * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be sent to the given <code>url</code> or <code>null</code> if no content * should be sent. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout in milliseconds to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong * @throws IOException when the request execution failed, timed out or it was interrupted */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) throws IOException { ContentResponse response = executeUrlAndGetReponse(httpMethod, url, httpHeaders, content, contentType, timeout, proxyHost, proxyPort, proxyUser, proxyPassword, nonProxyHosts); String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim() : "UTF-8"; String responseBody; try { responseBody = new String(response.getContent(), encoding); } catch (UnsupportedEncodingException e) { responseBody = null; } return responseBody; }