List of usage examples for org.apache.http.entity ContentType getCharset
public Charset getCharset()
From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java
private void setTextOfEntry(HarEntry entry, ByteArrayOutputStream copy, String contentType) { ContentType contentTypeCharset = ContentType.parse(contentType); Charset charset = contentTypeCharset.getCharset(); if (charset != null) { entry.getResponse().getContent().setText(new String(copy.toByteArray(), charset)); } else {//from w w w. j av a2 s . c o m entry.getResponse().getContent().setText(new String(copy.toByteArray())); } }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties, ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset) throws Exception { String method = httpDispatcherProperties.getMethod(); boolean isMultipart = httpDispatcherProperties.isMultipart(); Map<String, List<String>> headers = httpDispatcherProperties.getHeaders(); Map<String, List<String>> parameters = httpDispatcherProperties.getParameters(); Object content = null;//from w w w. j a v a 2 s . co m if (httpDispatcherProperties.isDataTypeBinary()) { content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(), connectorMessage, null, true); } else { content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(), connectorMessage); // If text mode is used and a specific charset isn't already defined, use the one from the connector properties if (contentType.getCharset() == null) { contentType = HttpMessageConverter.setCharset(contentType, charset); } } // populate the query parameters List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size()); for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) { for (String value : parameterEntry.getValue()) { logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]"); queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value)); } } HttpRequestBase httpMethod = null; HttpEntity httpEntity = null; URIBuilder uriBuilder = new URIBuilder(hostURI); // create the method if ("GET".equalsIgnoreCase(method)) { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpGet(uriBuilder.build()); } else if ("POST".equalsIgnoreCase(method)) { if (isMultipart) { logger.debug("setting multipart file content"); setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPost(uriBuilder.build()); if (content instanceof String) { FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false); } else { FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart(tempFile.getName(), new FileBody(tempFile, contentType, tempFile.getName())); httpEntity = multipartEntityBuilder.build(); } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(), ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { httpMethod = new HttpPost(uriBuilder.build()); httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset()); } else { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPost(uriBuilder.build()); if (content instanceof String) { httpEntity = new StringEntity((String) content, contentType); } else { httpEntity = new ByteArrayEntity((byte[]) content); } } } else if ("PUT".equalsIgnoreCase(method)) { if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(), ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { httpMethod = new HttpPut(uriBuilder.build()); httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset()); } else { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPut(uriBuilder.build()); if (content instanceof String) { httpEntity = new StringEntity((String) content, contentType); } else { httpEntity = new ByteArrayEntity((byte[]) content); } } } else if ("DELETE".equalsIgnoreCase(method)) { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpDelete(uriBuilder.build()); } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { // Compress the request entity if necessary List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers) .get(HTTP.CONTENT_ENCODING); if (CollectionUtils.isNotEmpty(contentEncodingList)) { for (String contentEncoding : contentEncodingList) { if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip") || contentEncoding.toLowerCase().equals("x-gzip"))) { httpEntity = new GzipCompressingEntity(httpEntity); break; } } } ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity); } // set the headers for (Entry<String, List<String>> headerEntry : headers.entrySet()) { for (String value : headerEntry.getValue()) { logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]"); httpMethod.addHeader(headerEntry.getKey(), value); } } // Only set the Content-Type for entity-enclosing methods, but not if multipart is used if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) { httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString()); } return httpMethod; }
From source file:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java
/** * If httpResponse must be transformed, creates an instance of * WIPTransformer, executes WIPTransformer#transform on the response content * and updates the response entity accordingly. * //from w w w .j a va 2 s. co m * @param httpResponse * @param context * @throws HttpException * @throws IOException */ public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException { PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest(); PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse(); WIPConfiguration config = WIPUtil.getConfiguration(portletRequest); RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest(); if (httpResponse == null) { // No response -> no transformation LOG.warning("No response to transform."); return; } HttpEntity entity = httpResponse.getEntity(); if (entity == null) { // No entity -> no transformation return; } ContentType contentType = ContentType.getOrDefault(entity); String mimeType = contentType.getMimeType(); String actualURL; RedirectLocations redirectLocations = (RedirectLocations) context .getAttribute("http.protocol.redirect-locations"); if (redirectLocations != null) actualURL = Iterables.getLast(redirectLocations.getAll()).toString(); else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) { actualURL = request.getRequestedURL(); } else { HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri(); } // Check if actual URI must be transformed if (!config.isProxyURI(actualURL)) return; // a builder for creating a WIPTransformer instance TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL) .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse) .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool); // Creates an instance of Transformer depending on ResourceType and // MimeType int status = transformerBuilder.build(); if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION) return; WIPTransformer transformer = transformerBuilder.getTransformer(); // Call WIPTransformer#transform method and update the response Entity // object try { String content = EntityUtils.toString(entity); String transformedContent = ((AbstractTransformer) transformer).transform(content); StringEntity transformedEntity; if (contentType.getCharset() != null) { transformedEntity = new StringEntity(transformedContent, contentType); } else { transformedEntity = new StringEntity(transformedContent); } transformedEntity.setContentType(contentType.toString()); httpResponse.setEntity(transformedEntity); } catch (SAXException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } catch (TransformerException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } }
From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java
protected static String readResponseAsString(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream is = entity.getContent(); try {//from w ww. j a va 2s .co m Charset charSet; try { ContentType ct = ContentType.get(entity); if (ct == null) charSet = StandardCharsets.UTF_8; else charSet = ct.getCharset(); } catch (ParseException e) { charSet = StandardCharsets.UTF_8; } char[] buffer = new char[65536]; Reader r = new InputStreamReader(is, charSet); Writer w = new StringWriter(); try { while (true) { int amt = r.read(buffer); if (amt == -1) break; w.write(buffer, 0, amt); } } finally { w.flush(); } return w.toString(); } finally { is.close(); } } return ""; }
From source file:org.apereo.portal.portlet.container.PortletResourceResponseContextImpl.java
/** * Handles resource response specific headers. Returns true if the header was consumed by this method and requires no further processing * //from w w w.ja v a 2s.c o m * @return */ protected boolean handleResourceHeader(String key, String value) { if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) { this.portletResourceOutputHandler.setStatus(Integer.parseInt(value)); return true; } if ("Content-Type".equals(key)) { final ContentType contentType = ContentType.parse(value); final Charset charset = contentType.getCharset(); if (charset != null) { this.portletResourceOutputHandler.setCharacterEncoding(charset.name()); } this.portletResourceOutputHandler.setContentType(contentType.getMimeType()); return true; } if ("Content-Length".equals(key)) { this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value)); return true; } if ("Content-Language".equals(key)) { final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null); if (parts.length > 0) { final String localeStr = parts[0].getValue(); final Locale locale = LocaleUtils.toLocale(localeStr); this.portletResourceOutputHandler.setLocale(locale); return true; } } return false; }
From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java
private Charset getCharset(byte[] content, String contentType) throws IOException { ContentType type = ContentType.parse(contentType); Charset charset = type.getCharset(); if (charset != null) return charset; ByteArrayInputStream in = new ByteArrayInputStream(content); try {//from w w w.ja va 2s. c om return new CharsetDetector().detect(in); } finally { in.close(); } }