List of usage examples for org.apache.http.entity ContentType get
public static ContentType get(HttpEntity httpEntity) throws ParseException, UnsupportedCharsetException
From source file:com.sina.cloudstorage.util.URLEncodedUtils.java
/** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an * {@link HttpEntity}. The encoding is taken from the entity's * Content-Encoding header.//w ww .j a va 2 s.co m * <p> * This is typically used while parsing an HTTP POST. * * @param entity * The entity to parse * @throws IOException * If there was an exception getting the entity's data. */ public static List<NameValuePair> parse(final HttpEntity entity) throws IOException { ContentType contentType = ContentType.get(entity); if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { String content = EntityUtils.toString(entity, Consts.ASCII); if (content != null && content.length() > 0) { Charset charset = contentType != null ? contentType.getCharset() : null; if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return parse(content, charset); } } return Collections.emptyList(); }
From source file:ca.uhn.fhir.rest.client.apache.ApacheHttpResponse.java
@Override public Reader createReader() throws IOException { HttpEntity entity = myResponse.getEntity(); if (entity == null) { return new StringReader(""); }/*from w w w. j a v a 2 s.c o m*/ Charset charset = null; if (entity.getContentType() != null && entity.getContentType().getElements() != null && entity.getContentType().getElements().length > 0) { ContentType ct = ContentType.get(entity); charset = ct.getCharset(); } if (charset == null) { if (Constants.STATUS_HTTP_204_NO_CONTENT != myResponse.getStatusLine().getStatusCode()) { ourLog.warn("Response did not specify a charset."); } charset = Charset.forName("UTF-8"); } Reader reader = new InputStreamReader(readEntity(), charset); return reader; }
From source file:com.sangupta.jerry.http.WebResponseHandler.java
/** * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse) *//*from www . ja v a2 s. co m*/ @Override public WebResponse handleResponse(HttpResponse response, HttpContext localHttpContext) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); byte[] bytes = null; if (entity != null) { bytes = EntityUtils.toByteArray(entity); } final WebResponse webResponse = new WebResponse(bytes); // decipher from status line webResponse.responseCode = statusLine.getStatusCode(); webResponse.message = statusLine.getReasonPhrase(); // set size if (entity != null) { webResponse.size = entity.getContentLength(); } else { long value = 0; Header header = response.getFirstHeader(HttpHeaders.CONTENT_LENGTH); if (header != null) { String headerValue = header.getValue(); if (AssertUtils.isNotEmpty(headerValue)) { try { value = Long.parseLong(headerValue); } catch (Exception e) { // eat the exception } } } webResponse.size = value; } // content type if (entity != null && entity.getContentType() != null) { webResponse.contentType = entity.getContentType().getValue(); } // response headers final Header[] responseHeaders = response.getAllHeaders(); if (AssertUtils.isNotEmpty(responseHeaders)) { for (Header header : responseHeaders) { webResponse.headers.put(header.getName(), header.getValue()); } } // charset try { ContentType type = ContentType.get(entity); if (type != null) { webResponse.charSet = type.getCharset(); } } catch (UnsupportedCharsetException e) { // we are unable to find the charset for the content // let's leave it to be considered binary } // fill in the redirect uri chain RedirectLocations locations = (RedirectLocations) localHttpContext .getAttribute(HttpClientContext.REDIRECT_LOCATIONS); if (AssertUtils.isNotEmpty(locations)) { webResponse.setRedirectChain(locations.getAll()); } // return the object finally return webResponse; }
From source file:com.redhat.jenkins.plugins.bayesian.Bayesian.java
public BayesianStepResponse submitStackForAnalysis(Collection<FilePath> manifests) throws BayesianException { String stackAnalysesUrl = getApiUrl() + "/stack-analyses"; HttpPost httpPost = new HttpPost(stackAnalysesUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (FilePath manifest : manifests) { byte[] content = null; try (InputStream in = manifest.read()) { content = ByteStreams.toByteArray(in); builder.addBinaryBody("manifest[]", content, ContentType.DEFAULT_BINARY, manifest.getName()); } catch (IOException | InterruptedException e) { throw new BayesianException(e); } finally { content = null;// w ww. j a v a2 s . c om } } HttpEntity multipart = builder.build(); builder = null; httpPost.setEntity(multipart); httpPost.setHeader("Authorization", "Bearer " + getAuthToken()); BayesianResponse responseObj = null; Gson gson; try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(httpPost)) { HttpEntity entity = response.getEntity(); // Yeah, the endpoint actually returns 200 from some reason; // I wonder what happened to the good old-fashioned 202 :) if (response.getStatusLine().getStatusCode() != 200) { throw new BayesianException("Bayesian error: " + response.getStatusLine().getStatusCode()); } Charset charset = ContentType.get(entity).getCharset(); try (InputStream is = entity.getContent(); Reader reader = new InputStreamReader(is, charset != null ? charset : HTTP.DEF_CONTENT_CHARSET)) { gson = new GsonBuilder().create(); responseObj = gson.fromJson(reader, BayesianResponse.class); String analysisUrl = stackAnalysesUrl + "/" + responseObj.getId(); return new BayesianStepResponse(responseObj.getId(), "", analysisUrl, true); } } catch (IOException e) { throw new BayesianException("Bayesian error", e); } finally { // just to be sure... responseObj = null; httpPost = null; multipart = null; gson = null; } }
From source file:com.helger.httpclient.response.ExtendedHttpResponseException.java
@Nonnull public static ExtendedHttpResponseException create(@Nonnull final StatusLine aStatusLine, @Nonnull final HttpResponse aHttpResponse, @Nonnull final HttpEntity aEntity) throws IOException { ContentType aContentType = ContentType.get(aEntity); if (aContentType == null) aContentType = ContentType.DEFAULT_TEXT; // Default to ISO-8859-1 internally final Charset aCharset = HttpClientHelper.getCharset(aContentType); // Consume entity final byte[] aResponseBody = EntityUtils.toByteArray(aEntity); return new ExtendedHttpResponseException(aStatusLine, aHttpResponse, aResponseBody, aCharset); }
From source file:cn.wanghaomiao.seimi.http.hc.HcDownloader.java
private Response renderResponse(HttpResponse httpResponse, Request request, HttpContext httpContext) { Response seimiResponse = new Response(); HttpEntity entity = httpResponse.getEntity(); seimiResponse.setSeimiHttpType(SeimiHttpType.APACHE_HC); seimiResponse.setRealUrl(getRealUrl(httpContext)); seimiResponse.setUrl(request.getUrl()); seimiResponse.setRequest(request);/*from www . j a v a 2 s. co m*/ seimiResponse.setMeta(request.getMeta()); if (entity != null) { Header referer = httpResponse.getFirstHeader("Referer"); if (referer != null) { seimiResponse.setReferer(referer.getValue()); } String contentTypeStr = entity.getContentType().getValue().toLowerCase(); if (contentTypeStr.contains("text") || contentTypeStr.contains("json") || contentTypeStr.contains("ajax")) { seimiResponse.setBodyType(BodyType.TEXT); try { seimiResponse.setData(EntityUtils.toByteArray(entity)); ContentType contentType = ContentType.get(entity); Charset charset = contentType.getCharset(); if (charset == null) { seimiResponse.setContent(new String(seimiResponse.getData(), "ISO-8859-1")); String docCharset = renderRealCharset(seimiResponse); seimiResponse.setContent( new String(seimiResponse.getContent().getBytes("ISO-8859-1"), docCharset)); seimiResponse.setCharset(docCharset); } else { seimiResponse.setContent(new String(seimiResponse.getData(), charset)); seimiResponse.setCharset(charset.name()); } } catch (Exception e) { logger.error("no content data"); } } else { seimiResponse.setBodyType(BodyType.BINARY); try { seimiResponse.setData(EntityUtils.toByteArray(entity)); seimiResponse.setContent(StringUtils.substringAfterLast(request.getUrl(), "/")); } catch (Exception e) { logger.error("no data can be read from httpResponse"); } } } return seimiResponse; }
From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java
static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext) throws OIDCClientException, SSLConnectionException { Validate.notNull(httpRequest, "httpRequest"); Validate.notNull(sslContext, "sslContext"); RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build(); CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config) .build();/*from w ww .j a v a 2s . co m*/ CloseableHttpResponse closeableHttpResponse = null; try { HttpRequestBase httpTask = httpRequest.toHttpTask(); closeableHttpResponse = client.execute(httpTask); int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode(); StatusCode statusCode; try { statusCode = StatusCode.parse(statusCodeInt); } catch (ParseException e) { throw new OIDCClientException("failed to parse status code", e); } JSONObject jsonContent = null; HttpEntity httpEntity = closeableHttpResponse.getEntity(); if (httpEntity != null) { ContentType contentType; try { contentType = ContentType.get(httpEntity); } catch (UnsupportedCharsetException | org.apache.http.ParseException e) { throw new OIDCClientException("Error in setting content type in HTTP response."); } if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) { throw new OIDCClientException("unsupported charset: " + contentType.getCharset()); } if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) { throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType()); } String content = EntityUtils.toString(httpEntity); try { jsonContent = JSONUtils.parseJSONObject(content); } catch (ParseException e) { throw new OIDCClientException("failed to parse json response", e); } } closeableHttpResponse.close(); client.close(); return HttpResponse.createJsonResponse(statusCode, jsonContent); } catch (IOException e) { throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e); } }
From source file:de.drv.dsrv.spoc.web.service.impl.SpocResponseHandler.java
/** * Versucht, das Charset des Payloads aus dem HTTP-Header * <code>Content-Type</code> zu bestimmen. * // w ww . j a v a 2 s . c o m * @param httpResponseEntity * die Response des Fachverfahrens * * @return das in der Response verwendete Charset, oder <code>null</code>, * wenn kein Charset bestimmt werden konnte */ private Charset getCharsetFromResponse(final HttpEntity httpResponseEntity) { ContentType contentType; try { contentType = ContentType.get(httpResponseEntity); } catch (final RuntimeException exc) { LOG.warn("Fehler beim Auslesen des Content-Types aus der Response.", exc); return null; } if (contentType == null) { if (LOG.isInfoEnabled()) { LOG.info( "Es konnte kein Content-Type und somit auch kein Charset aus der Response gelesen werden."); } return null; } return contentType.getCharset(); }
From source file:com.hzq.car.CarTest.java
/** * ??post,json//from w ww. ja v a 2s. co m */ private String sendAndGetResponse(String url, List<NameValuePair> params) throws IOException { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); StringBuilder messageBuilder = new StringBuilder("\n"); messageBuilder.append(post.getMethod()); messageBuilder.append(" "); messageBuilder.append(post.getURI()); messageBuilder.append(" "); HttpEntity entity = post.getEntity(); String body = IOUtils.toString(entity.getContent()); List<NameValuePair> parse = URLEncodedUtils.parse(body, ContentType.get(entity).getCharset()); parse.stream().forEach(pair -> { messageBuilder.append(pair.getName()); messageBuilder.append(":"); messageBuilder.append(pair.getValue()); messageBuilder.append(" "); }); logger.warn("send httpRequest: {}", messageBuilder.toString()); CloseableHttpResponse response = client.execute(post); InputStream content = response.getEntity().getContent(); String s = IOUtils.toString(content); response.close(); logger.warn("get httpResponse: \n{}", s); return s; }
From source file:co.cask.cdap.client.rest.RestClient.java
/** * Utility method for converting {@link org.apache.http.HttpEntity} HTTP entity content to String. * * @param httpEntity {@link org.apache.http.HttpEntity} * @return {@link String} generated from input content stream * @throws IOException if HTTP entity is not available */// w w w. ja v a 2s .co m public static String toString(HttpEntity httpEntity) throws IOException { if (httpEntity == null || httpEntity.getContent() == null) { throw new IOException("Empty HttpEntity is received."); } Charset charset = Charsets.UTF_8; ContentType contentType = ContentType.get(httpEntity); if (contentType != null && contentType.getCharset() != null) { charset = contentType.getCharset(); } Reader reader = new InputStreamReader(httpEntity.getContent(), charset); try { return CharStreams.toString(reader); } finally { reader.close(); } }